重写数组拓展方法

forEach
Array.prototype.myforEach function (fn) {
    var arr = this,
        length = arr.length,
        newThis = arguments[1] || global;
    for (var index = 0; index < length; index++) {
        fn.apply(newThis, [arr[index], index, arr])
    }

}
map Array.prototype.myMap 
function (fn) {     var arr = this,         length = arr.length,         newThis = arguments[1] || global;     newArr = [];     for (var index = 0; index < length; index++) {         newArr.push(fn.apply(newThis, [arr[index], index, arr]))     }     return newArr }
filter Array.prototype.myFilter 
function (fn) {     var arr = this,         length = arr.length,         newThis = arguments[1] || global,         newArr = [];     for (var index = 0; index < length; index++) {         fn.apply(newThis, [arr[index], index, arr]) ? newArr.push(arr[index]) : null     }     return newArr }
every Array.prototype.myEvery 
function (fn) {     var arr = this,         length = arr.length,         newThis = arguments[1] || global;     for (var index = 0; index < length; index++) {         if (!fn.apply(newThis, [arr[index], index, arr])) {             return false         }     }     return true }
some Array.prototype.mySome 
function (fn) {     var arr = this,         length = arr.length,         newThis = arguments[1] || global;     for (var index = 0; index < length; index++) {         if (fn.apply(newThis, [arr[index], index, arr])) {             return true         }     }     return false }
reduce Array.prototype.myReduce 
function (fn, initValue) {     var arr = this,         length = arr.length,         newThis = arguments[2] || global;     for (var index = 0; index < length; index++) {         initValue = fn.apply(newThis, [initValue, arr[index], index, arr])     }     return initValue }
reduceRight Array.prototype.myReduceRight 
function (fn, initValue) {     var arr = this,         length = arr.length,         newThis = arguments[2] || global;     for (var index = length; index--;) {         initValue = fn.apply(newThis, [initValue, arr[index], index, arr])     }     return initValue }

 

posted on 2021-01-30 11:12  sss大辉  阅读(72)  评论(0编辑  收藏  举报

导航