[英]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.