只有在循环数组时才执行else语句

时间:2018-04-10 06:46:17

标签: javascript jquery

我有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数据执行。我在这里做错了什么?< / p>

2 个答案:

答案 0 :(得分:1)

请改为尝试:

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')
}

答案 1 :(得分:0)

您的意思是显示所有位置大小的警报吗?

allLocation.forEach(function(al) {
    currentLocation.forEach(function(cl){
        if(cl.locationCode == al.locationCode){
            alert ("Inside location")
        } else {
            alert ("Out of location")
        } 
    }) 
}) 
相关问题