javascript - 在 Javascript 数组中结合 indexOf 和 regexp 匹配
问题描述
我需要返回包含false
在数组中的字符串的位置。
["2: true", "4: true", "7: false", "8: true", "10: true"]
下面的代码返回位置重置的新数组,应该是2
.
return arrCom.filter(s => s.includes("false"));
解决方案
不需要正则表达式或indexOf
. 要查找与任意标准匹配的数组中第一个条目的索引,请使用findIndex
:
const index = array.findIndex(entry => entry.includes("false"));
现场示例:
const array = ["2: true", "4: true", "7: false", "8: true", "10: true"];
const index = array.findIndex(entry => entry.includes("false"));
console.log(index);
如果你想要条目本身,你会使用find
.
如果可能有多个匹配项并且您想要它们的所有索引,最简单的方法是使用循环:
const indexes = [];
for (let i = 0; i < array.length; ++i) {
if (array[i].includes("false")) {
indexes.push(i);
}
}
现场示例:
const array = ["2: true", "4: true", "7: false", "8: true", "10: true"];
const indexes = [];
for (let i = 0; i < array.length; ++i) {
if (array[i].includes("false")) {
indexes.push(i);
}
}
console.log(index);
推荐阅读
- c# - 各种类如何只使用日志文件类的一个实例
- ajax - Laravel 发布 - 419 未知状态
- java - 如何使用fabric8 java客户端API在Kubernetes中执行滚动更新和部署回滚?
- swift - 无法调用非函数类型“UITableView?”的值 在 UITapGestureRecognizer 方法中
- powerapps - powerapps 中的日历事件
- python - 给定开始和停止时间,检查服务是否应该开启
- python - 如何根据标题行将数据帧拆分为多个数据帧
- autodesk-forge - 在 Forge Viewer 中限制轨道运动
- pyspark - 使用 spark -redshift 连接器将 spark 连接到 redshift 时出现问题
- javascript - JavaScript / AngularJS 中的应用程序洞察力