-1

什么是通用 indexOf 垫片函数,它需要一个数组和一个值来匹配,在可用的地方利用本机函数?

4

1 回答 1

0
indexOf = (function() {
    if(typeof Array.prototype.indexOf === "function") {
        return function(haystack, needle, fromIndex){
            return haystack.indexOf(needle, fromIndex);
        };
    }
    return function(haystack, needle, fromIndex) {
        var l = haystack.length, 
            i = (typeof fromIndex === "undefined" ? 0 : (fromIndex < 0 ? l + fromIndex : fromIndex)), 
            index = -1;
        for(i; i < l; ++i) {
            if(haystack[i] === needle) {
                index = i;
                break;
            }
        }
        return index;
    };
})();

利用:

indexOf(["apples", "oranges", "bananas"], "apples");
//returns 0

indexOf(["oranges", "apples", "bananas"], "apples", 1);
//returns 1

-1如果没有找到则返回。

于 2014-01-14T20:02:42.757 回答