我有2个数组currentLocation and allLocation

currentLocation =[
    {
      "name":"AAA",
      "locationCode":"room"
    }
    ];

    allLocation=[
    {
      "name":"SSS",
      "locationCode":"Hall"
    },
    {
      "name":"PPP",
      "locationCode":"Building"
    },
    {
      "name":"SSS",
      "locationCode":"room"
    }
];


我正在检查所有currentLocation数据和所有allLocation数据,如果匹配则返回alert("Inside Location")否则应返回alert("Out of location")

这是代码:

currentLocation.forEach(function(eq){

        var valid=false;
        allLocation.forEach(function(d){
          if(d.locationCode==eq.locationCode){
            alert("Inside location")
            valid=true;
          }
        })
        if(!valid){
            alert('Out of location')
        }

    })


我的查询是if(!valid)应该在将currentLocation数据与所有allLocation数据进行比较后执行。但是对每个allLocation数据执行它。我在这里做错了什么?

最佳答案

尝试以下方法:

currentLocation =[
{
    "name":"AAA",
    "locationCode":"room"
}
];

allLocation=[
{
    "name":"SSS",
    "locationCode":"Hall"
},
{
    "name":"PPP",
    "locationCode":"Building"
},
{
    "name":"SSS",
    "locationCode":"room"
}
];

var valid = false;
currentLocation.forEach(function(eq){
    allLocation.forEach(function(d){
        if(d.locationCode==eq.locationCode){
            alert ("Inside location")
            valid=true;
        }
    })
})

if(!valid){
    alert ('Out of location')
}

关于javascript - 仅在遍历数组时执行else语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49747106/

10-09 17:32