indexOf类似的函数在javascript中返回多个外观

时间:2013-07-11 17:25:02

标签: javascript

使用indexOf时,我可以找到第一个外观的位置:

例如:

a=[1,2,4,2];
b=a.indexOf(2);
alert(b) //returns 1

是否有任何替代函数indexOf找到这两个位置或我错过了什么?我正在寻找捷径。当然,我总是可以写一个简单的外观来找到它。

4 个答案:

答案 0 :(得分:5)

indexOf采用第二个参数(起始索引)

所以a.indexOf(2,2)会给你3

要概括,如果x = a.indexOf(2),则下一个实例为a.indexOf(2, x+1)

答案 1 :(得分:2)

function indexesOf(arr, target) {
  // Map matching elements to their index, and others to null.
  return arr.map(function (el, i) { return (el === target) ? i : null; })
            // Throw out the nulls.
            .filter(function (x) { return x !== null; });
}

alert(indexesOf([1, 2, 4, 2], 2));  // -> 1, 3

答案 2 :(得分:1)

当您使用最近的ECMAScript 5方法时,您可能需要考虑使用Array.mapArray.filter以及新的Harmony建议方法Object.is

的Javascript

var func = {}.is,
    is;

if (typeof func === "function") {
    is = func;
} else {
    is = function is(x, y) {
        if (x === y) {
            if (x === 0) {
                return 1 / x === 1 / y;
            }

            return true;
        }

        var x1 = x,
            y1 = y;

        return x !== x1 && y !== y1;
    };
}

function indexesOf(array, value) {
    if (!Array.isArray(array)) {
        throw new TypeError("First attribute must be an array.");
    }

    return array.map(function (element, index) {
        if (is(value, element)) {
            return index;
        }
    }).filter(function (element) {
        return typeof element === "number";
    });
}

var test = [1, 2, 4, 2];

console.log(indexesOf(test, 2));

输出

[1, 3] 

jsfiddle

更新: 过去,当人们有坚定的信念使用循环时,我一直受到严厉批评“但这正是这些新方法的设计目标”。所以,我也将提出替代的单循环解决方案。

ECMAScript 5 Array.reduce

的Javascript

function indexesOf(array, value) {
    if (!Array.isArray(array)) {
        throw new TypeError("First attribute must be an array.");
    }

    return array.reduce(function (previous, current, index) {
        if (is(value, current)) {
            previous.push(index);
        }

        return previous;
    }, []);
}

jsfiddle

ECMAScript 5 Array.forEach

的Javascript

function indexesOf(array, value) {
    if (!Array.isArray(array)) {
        throw new TypeError("First attribute must be an array.");
    }

    var indexes = [];

    array.forEach(function (element, index) {
        if (is(value, element)) {
            indexes.push(index);
        }
    });

    return indexes.
}

jsfiddle

ECMAScript 5 Array.indexOf

注意:此方法无法找到 NaN的索引

还可以使用Array.lastIndexOf并反向工作

的Javascript

function indexesOf(array, value) {
    if (!Array.isArray(array)) {
        throw new TypeError("First attribute must be an array.");
    }

    var index = array.indexOf(value),
        indexes = [];

    while (index !== -1) {
        indexes.push(index);
        index = array.indexOf(value, index + 1);
    }

    return indexes;
}

jsfiddle

标准for

的Javascript

function indexesOf(array, value) {
    if ({}.toString.call(array) !== "[object Array]") {
        throw new TypeError("First attribute must be an array.");
    }

    var indexes = [],
        length,
        index;

    for (index = 0, length = array.length; index < length; index += 1) {
        if (array.hasOwnProperty(index) && is(value, array[index])) {
            indexes.push(index);
        }
    }

    return indexes;
}

jsfiddle

标准while

的Javascript

function indexesOf(array, value) {
    if ({}.toString.call(array) !== "[object Array]") {
        throw new TypeError("First attribute must be an array.");
    }

    var length = array.length,
        indexes = []
        index = 0;

    while (index < length) {
        if (array.hasOwnProperty(index) && is(value, array[index])) {
            indexes.push(index);
        }

        index += 1;
    }

    return indexes;
}

jsfiddle

标准for...in

注意:不建议这样做,但应该没问题。

Why is using “for…in” with array iteration such a bad idea?

的Javascript

function indexesOf(array, value) {
    if ({}.toString.call(array) !== "[object Array]") {
        throw new TypeError("First attribute must be an array.");
    }

    var indexes = [],
        prop;

    for (prop in array) {
        if (array.hasOwnProperty(prop) && is(+prop, prop >>> 0) && is(value, array[prop])) {
            indexes.push(+prop);
        }
    }

    return indexes;
}

jsfiddle

注意:此处的所有解决方案都处理密集和稀疏数组。

最后一个jsperf比较了所有这些解决方案。

答案 3 :(得分:0)

lastIndexOf()给出最后一次出现的索引。

但是如果想要一个包含特定元素的所有出现的索引数组(在你的情况下为2),你必须编写一个循环。