我无法找到正确的方法来查找for
循环中的项是否在数组中。假设我有一个for
循环正在遍历一些结果。如果它们在数组中:
ctids = [];
继续进行for
循环中的下一步,如果没有,则将它们推入数组并执行其他操作。正确的语法是什么?
for (var i=0;i<results.features.length;i++){
ACS_BG = results.features[i].attributes.BLKGRPCE;
ACS_ST = results.features[i].attributes.STATEFP;
ACS_CNTY = results.features[i].attributes.COUNTYFP;
ACS_TRCT = results.features[i].attributes.TRACTCE;
if ACS_TRCT exists in ctids { //This is where I am having trouble.
continue; //skip the rest of the if statement
} else {
ctids.push(ACS_TRCT);
// do something else;
};
};
答案 0 :(得分:1)
您可以使用include检查元素是否存在于数组中,以及是否不将元素压入其中。
if (ctids.includes(ACS_TRCT)){
continue;
}else{
ctids.push(ACS_TRCT)
}
答案 1 :(得分:1)
我愿意:
for (var i = 0; i < results.features.length; i++) {
const ACS_BG = results.features[i].attributes.BLKGRPCE;
const ACS_ST = results.features[i].attributes.STATEFP;
const ACS_CNTY = results.features[i].attributes.COUNTYFP;
const ACS_TRCT = results.features[i].attributes.TRACTCE;
// push ACS_TRCT, ACS_ST, ACS_TRCT, ACS_CNTY to resulting
// array ctids if they don't present using `.includes` method.
if (!ctids.includes(ACS_TRCT)) ctids.push(ACS_TRCT);
if (!ctids.includes(ACS_ST)) ctids.push(ACS_ST);
if (!ctids.includes(ACS_CNTY)) ctids.push(ACS_CNTY);
if (!ctids.includes(ACS_TRCT)) ctids.push(ACS_TRCT);
}
答案 2 :(得分:1)
请您尝试以下代码
var ctids = []
for (var i=0;i<results.features.length;i++){
ACS_BG = results.features[i].attributes.BLKGRPCE;
ACS_ST = results.features[i].attributes.STATEFP;
ACS_CNTY = results.features[i].attributes.COUNTYFP;
ACS_TRCT = results.features[i].attributes.TRACTCE;
if(!ctids.includes(ACS_TRCT))
{
ctids.push(ACS_TRCT);
}
};
答案 3 :(得分:0)
您可以使用.find
来检查数组中是否已存在该项(仅适用于基本类型)
var found = ctids.find(function(value) {
return ACS_TRCT === value;
});
if(!found) {
ctids.push(ACS_TRCT);
}