具有多个值的Javascript indexOf方法

5 javascript arrays indexof

我有一个array包含多个相同值的数据

["test234", "test9495", "test234", "test93992", "test234"]
Run Code Online (Sandbox Code Playgroud)

在这里,我想得到test234数组中每个的索引

为此,我尝试了Array.prototype.indexOf()方法.但它只会让我0回归,但我希望它能归还给我[0, 2, 4].

我怎样才能做到这一点?

var array = ["test234", "test9495", "test234", "test93992", "test234"];
document.write(array.indexOf("test234"));
Run Code Online (Sandbox Code Playgroud)

ZER*_*ER0 10

您可以使用减少

const indexesOf = (arr, item) => 
  arr.reduce(
    (acc, v, i) => (v === item && acc.push(i), acc),
  []);
Run Code Online (Sandbox Code Playgroud)

所以:

const array = ["test234", "test9495", "test234", "test93992", "test234"];
console.log(indexesOf(array, "test234")); // [0, 2, 4]
Run Code Online (Sandbox Code Playgroud)

另一种方法可能是使用迭代器

function* finder(array, item) {
  let index = -1;
  while ((index = array.indexOf(item, index + 1)) > -1) {
    yield index;
  }
  return -1;
}
Run Code Online (Sandbox Code Playgroud)

这使您可以灵活地以惰性方式进行搜索,只有在需要时才可以进行搜索:

let findTest234 = finder(array, "test234");

console.log(findTest234.next()) // {value: 0, done: false}
console.log(findTest234.next()) // {value: 2, done: false}
console.log(findTest234.next()) // {value: 4, done: false}    
console.log(findTest234.next()) // {value: -1, done: true}
Run Code Online (Sandbox Code Playgroud)

当然,您始终可以在循环中使用它(因为它是一个迭代器):

let indexes = finder(array, "test234");

for (let index of indexes) {
   console.log(index);
}
Run Code Online (Sandbox Code Playgroud)

并立即使用迭代器来生成数组:

let indexes = [...finder(array, "test234")];
console.log(indexes); // [0, 2, 4]
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。


4ca*_*tle 8

这种功能不存在内置,但自己制作它会很容易。值得庆幸的是,indexOf还可以接受起始索引作为第二个参数。

function indexOfAll(array, searchItem) {
  var i = array.indexOf(searchItem),
      indexes = [];
  while (i !== -1) {
    indexes.push(i);
    i = array.indexOf(searchItem, ++i);
  }
  return indexes;
}

var array = ["test234", "test9495", "test234", "test93992", "test234"];
document.write(JSON.stringify(indexOfAll(array, "test234")));
Run Code Online (Sandbox Code Playgroud)


Joe*_*oeL 7

只需将其设为for循环即可检查每个数组元素.

var array = ["test234", "test9495", "test234", "test93992", "test234"];

for (i=0;i<array.length;i++) {
  if (array[i] == "test234") {
    document.write(i + "<br>");
  }
}
Run Code Online (Sandbox Code Playgroud)