zat*_*nik 1 javascript arrays indexof
我试图让 indexOf 返回值等于“1”(完全匹配)的数组项的多个索引。
这是我在做什么:
var arr = [1, 11, 1, 111, 1111, 11, 1, 1111, 11];
for (i = 0; i < arr.length; i++){
console.log(arr.findIndex(1, i));
}
Run Code Online (Sandbox Code Playgroud)
我期望的结果是:0 2 6
但实际上我在提到索引后得到“-1”值。我假设它与数组的值有关(每个值都包含“1”但不等于“1”)。当我对不同值的数组做同样的事情时,它会按需要工作。
它真的与价值观有关吗?如果是,如何解决这个问题?如果有更合适的方法可以通过一个值(完全匹配)找到多个数组的索引,我们将不胜感激。
您可以将数组减少为索引数组,其值为1:
const arr = [1, 11, 1, 111, 1111, 11, 1, 1111, 11];
const indexes = arr.reduce((r, n, i) => {
n === 1 && r.push(i);
return r;
}, []);
console.log(indexes);Run Code Online (Sandbox Code Playgroud)
您还可以使用indexOf和while循环,从最后找到的索引开始搜索,并在索引为时停止-1:
const arr = [1, 11, 1, 111, 1111, 11, 1, 1111, 11];
let i = -1;
const indexes = [];
while(i = arr.indexOf(1, i + 1), i !== -1) indexes.push(i);
console.log(indexes);Run Code Online (Sandbox Code Playgroud)