【问题标题】:Using indexOf method on array, getting all indexes and not just first [duplicate]在数组上使用 indexOf 方法,获取所有索引,而不仅仅是第一个 [重复]
【发布时间】:2014-10-02 07:40:05
【问题描述】:

假设我有一个包含字符串的数组:

var array = ["test","apple","orange","test","banana"];

有些字符串是完全一样的(test)。假设我想获取数组中字符串 test 所在数组的所有索引,而不仅仅是第一个 indexOf。这个问题有没有一个很好的解决方案,尽可能快并且不使用 jQuery,结果 I.E 得到 0,2?

谢谢

【问题讨论】:

标签: javascript arrays indexof


【解决方案1】:

你可以像这样使用内置的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);

【讨论】:

    猜你喜欢
    • 2014-04-24
    • 2012-10-08
    • 2015-03-21
    • 2021-09-15
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    相关资源
    最近更新 更多