繁体   English   中英

仅在遍历数组时执行else语句

[英]Execute else statement only if looped through the array

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

    })

我的查询是一旦将currentLocation数据与所有allLocation数据进行比较,是否应该执行if(!valid) 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')
}

您是否要显示与所有位置大小一样多的警报?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM