gpt4 book ai didi

javascript - 如何在纯JavaScript中通过值获取数组的多个索引(值精确匹配)

转载 作者:行者123 更新时间:2023-11-28 14:29:01 25 4
gpt4 key购买 nike

我试图让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));
}

我期望的结果是:026

但实际上我在提到的索引后得到“-1”值。我假设它与数组有关值(每个值都包含“1”但不等于“1”)。当我对数组做同样的事情时不同的值,它按需要工作。

这真的和值(value)观有关吗?如果是,如何解决这个问题?如果有更合适的方法通过值查找多个数组的索引(精确匹配),我们将不胜感激。

最佳答案

您可以reduce数组到索引数组,值为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);

您还可以使用 indexOfwhile 循环,从最后找到的索引开始搜索,并在索引为 -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);

关于javascript - 如何在纯JavaScript中通过值获取数组的多个索引(值精确匹配),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52154331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com