美文网首页
ES5 数组方法封装

ES5 数组方法封装

作者: 鹤仔z | 来源:发表于2020-01-28 16:05 被阅读0次

forEach

Array.prototype.myForEach = function(callback){
    if(typeof callback !== 'function'){
        throw new Error(callback + 'is not function');
    }
    let T = arguments[1] ? arguments[1] : window;
    for(let i = 0 ; i < this.length ; i ++){
        callback.call(T,this[i],i,this)
    }
}

map

Array.prototype.myMap = function(callback){
    if(typeof callback !== 'function'){
        throw new Error(callback + 'is not function');
    }
    let T = arguments[1] ? arguments[1] : window;
    let res = [];
    for(let i = 0 ; i < this.length ; i ++){
        res.push(callback.call(T,this.[i],i,this));
    }
    return res;
}

filter

Array.prototype.myFilter = function(callback){
    if(typeof callback !== 'function'){
        throw new Error(callback + 'is not function');
    }
    let T = arguments[1] ? arguments[1] : window;
    let res = [];
    for(let i = 0 ; i < this.length ; i ++){
        if(callback.call(T,this[i],i,this)){
            res.push(this[i]);
        }
    }
    return res;
}

reduce

Array.prototype.maReduce = function(callback,I){
    if(typeof callback !== 'function'){
        throw new Error(callback + 'is not function');
    }
    var isI = false;
    var res;
    if(I){
        isI = true;
        res = I;
    }
    for(var i = 0 ; i < this.length ; i ++){
        if(isI){
            res = callback(res,this[i],i,this)
        }else{
            res = this[i];
            isI = true;
        }
    }
    return res;
}

相关文章

网友评论

      本文标题:ES5 数组方法封装

      本文链接:https://www.haomeiwen.com/subject/hyqboctx.html