javascript - 检查数组中的项目
问题描述
我无法找到正确的方法来查找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;
};
};
解决方案
您可以使用包含来检查元素是否存在于数组中,如果不存在则将元素推入其中。
if (ctids.includes(ACS_TRCT)){
continue;
}else{
ctids.push(ACS_TRCT)
}
推荐阅读
- database - 未在 toad 中运行的程序要求变量
- python - 使用python脚本调用属性文件并在其中匹配值
- c# - 如何在 Asp.Net Core Web App 中为模型的一个字段添加多个值?
- momentjs - 如何在没有警告的情况下将日期“2019 年 4 月 2 日”格式化为“YYYY-MM-DD”?
- input - 如何验证材料输入中的输入文本长度?
- angular - Ionic 4:让表单随每个输入而自我更新
- archlinux - pgadmin4 显示 500(内部服务器错误)
- python - Python while 循环正在暂停
- python - 使用带有 Python 的数据库跟踪在线用户
- python - 无法安装聊天机器人库