簡體   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