Array.indexOf垫片没有原型设计

时间:2014-01-14 20:02:43

标签: javascript arrays indexof shim

什么是通用indexOf shim函数,它使用可用的本机函数来获取数组和值以匹配?

1 个答案:

答案 0 :(得分: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