假设我有一个包含字符串的数组:
var array = ["test","apple","orange","test","banana"];
有些字符串是完全相同的(测试)。假设我想要获取数组中字符串 test 位于数组中的所有索引,而不仅仅是第一个 indexOf。有没有一个好的解决方案可以尽可能快地解决这个问题,并且不使用 jQuery,即结果为 0,2?
谢谢
最佳答案
您可以使用内置 Array.prototype.forEach
像这样
var indices = [];
array.forEach(function(currentItem, index) {
if (currentItem === "test") {
indices.push(index);
}
});
console.log(indices);
更好的是,您可以使用 Array.prototype.reduce
像这样
var indices = array.reduce(function(result, currentItem, index) {
if (currentItem === "test") {
result.push(index);
}
return result;
}, []);
console.log(indices);
由于您希望解决方案甚至可以在 IE 中工作,因此您可能需要使用普通的旧循环,如下所示
var indices = [], i;
for (i = 0; i < array.length; i += 1) {
if (array[i] === "test") {
indices.push(i);
}
}
console.log(indices);
关于javascript - 在数组上使用indexOf方法,获取所有索引而不仅仅是第一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26156289/