首页 > 解决方案 > 检查数组中的项目

问题描述

我无法找到正确的方法来查找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;
    };
};

标签: javascriptarraysif-statementoperators

解决方案


您可以使用包含来检查元素是否存在于数组中,如果不存在则将元素推入其中。

if (ctids.includes(ACS_TRCT)){
continue;
}else{
ctids.push(ACS_TRCT)
}

推荐阅读