如何通过纯JavaScript中的值获取数组的多个索引(值完全匹配)

How to get multiple indexes of array by a value in pure JavaScript (value exact matching)

我正在尝试使 indexOf return 成为数组项的多个索引,其值等于“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));
}

我期望的结果是: 0 2个 6

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

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

你可以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);

使用 Pure JavaScript 有多种方法可以做到这一点。我已经添加了其中一些。

使用Array.prototype.filter()

var arr = [1, 11, 1, 111, 1111, 11, 1, 1111, 11];
var keys = [];
var filtered = arr.filter((e, i) => {
  if (e === 1) {
    keys.push(i);
  }
});
console.log(keys);

使用Array.prototype.forEach()

var arr = [1, 11, 1, 111, 1111, 11, 1, 1111, 11];
var keys = [];
arr.forEach((e,i)=>{
  if(e === 1){
    keys.push(i);
  }
});
console.log(keys);

使用Array.prototype.reduce()

var arr = [1, 11, 1, 111, 1111, 11, 1, 1111, 11];
var keys = [];
arr.reduce(function(a, e, i) {
  if (e === 1)
    keys.push(i);
  return keys;
}, [])

console.log(keys);