首页 > 解决方案 > 在 Javascript 数组中结合 indexOf 和 regexp 匹配

问题描述

我需要返回包含false在数组中的字符串的位置。

[​"2: true", "4: true", ​"7: false", ​"8: true", ​"10: true"]

下面的代码返回位置重置的新数组,应该是2.

return arrCom.filter(s => s.includes("false"));

标签: javascriptarrayssortingfilter

解决方案


不需要正则表达式或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);


推荐阅读