Javascript 具有多个值的Javascript indexOf方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36631641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:19:40  来源:igfitidea点击:

Javascript indexOf method with multiple values

javascriptarraysindexof

提问by JoeL

I have an arraywich contains multiple same values

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

["test234", "test9495", "test234", "test93992", "test234"]

Here I want to get the index of every test234in the array

在这里我想获取test234数组中每个的索引

For that I've tried Array.prototype.indexOf()method. But It only returns me 0but I want it to return me [0, 2, 4].

为此,我尝试了Array.prototype.indexOf()方法。但它只返回我,0但我希望它返回我[0, 2, 4]

How can I do that?

我怎样才能做到这一点?

var array = ["test234", "test9495", "test234", "test93992", "test234"];
document.write(array.indexOf("test234"));

回答by JoeL

Just make it a for loop to check each array element.

只需让它成为一个 for 循环来检查每个数组元素。

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

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

回答by 4castle

This kind of function doesn't exist built in, but it would be pretty easy to make it yourself. Thankfully, indexOfcan also accept a starting index as the second parameter.

这种功能不存在内置,但自己制作它会很容易。值得庆幸的是,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")));

回答by Nina Scholz

You can use the fromIndexof Array#indexOf.

您可以使用fromIndexArray#indexOf

fromIndex

The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched. Default: 0 (entire array is searched).

从索引

开始搜索的索引。如果索引大于或等于数组的长度,则返回-1,这意味着不会搜索数组。如果提供的索引值为负数,则将其视为距数组末尾的偏移量。注意:如果提供的索引为负数,数组仍会从前到后搜索。如果计算出的索引小于 0,则将搜索整个数组。默认值:0(搜索整个数组)。

~is a bitwise not operator.

~按位非运算符

It is perfect for use with indexOf(), because indexOfreturns if found the index 0 ... nand if not -1:

value  ~value   boolean
-1  =>   0  =>  false
 0  =>  -1  =>  true
 1  =>  -2  =>  true
 2  =>  -3  =>  true
 and so on 

它非常适合与 一起使用indexOf(),因为indexOf如果找到索引0 ... n则返回,否则返回-1

value  ~value   boolean
-1  =>   0  =>  false
 0  =>  -1  =>  true
 1  =>  -2  =>  true
 2  =>  -3  =>  true
 and so on 

var array = ["test234", "test9495", "test234", "test93992", "test234"],
    result = [],
    pos = array.indexOf('test234');

while (~pos) {
    result.push(pos);
    pos = array.indexOf('test234', pos + 1); // use old position incremented
} //                               ^^^^^^^

document.write('<pre> ' + JSON.stringify(result, 0, 4) + '</pre>');

回答by Paul Kurtis

You may use indexOf with a for loop to get the index values of 0,2,4:

您可以在 for 循环中使用 indexOf 来获取 0,2,4 的索引值:

var array = ["test234", "test9495", "test234", "test93992", "test234"];
let newArr=[];
for (i=0;i<array.length;i++) {
  if (array[i].indexOf("test234") >=0 ) {
    newArr.push(i);
  }
}
document.write(newArr);

回答by ZER0

You can use reduce:

您可以使用减少

const indexesOf = (arr, item) => 
  arr.reduce(
    (acc, v, i) => (v === item && acc.push(i), acc),
  []);

So:

所以:

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

An alternative approach could be having an iterator:

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

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

That's give you the flexibility to have the search in a lazy way, you can do it only when you need it:

这使您可以灵活地以懒惰的方式进行搜索,您可以仅在需要时进行搜索:

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}

Of course, you can always use it in loops (since it's an iterator):

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

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

for (let index of indexes) {
   console.log(index);
}

And consume the iterator immediately to generate arrays:

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

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

Hope it helps.

希望能帮助到你。