ES5 Array 的扩展方法兼容

1.Array.forEach

ES5 中Array.forEach 接受一个 fn(param1, param2, param3),和一个context(上下文)参数,其中:

param1 : 数组中当前元素

param2 : 当前元素索引

param3 : 数组本身

兼容代码:

Array.prototype.forEach = Array.prototype.forEach || function(fn, context){
    if(this && Object.prototype.toString.call(fn) === '[object Function]'){
        for(var i = 0, len = this.length; i < len; i++){
            fn.call(context, this[i], i, this);
        }        
    }
}

var arr = [1, 2, 3],
    result = [], 
    b = {a : 1}
    ;
arr.forEach(function(a, b, c){
    console.log(this);
    result.push([a + 1, b, c]);    
}, b);
console.log(result);
// Object { a=1}
// Object { a=1}
// Object { a=1}
// [[2, 0, [1, 2, 3]], [3, 1, [1, 2, 3]], [4, 2, [1, 2, 3]]]

未完待续。。。

原文地址:https://www.cnblogs.com/jackliu6/p/3643442.html