js中Array要領重寫(二):myForEach;myEvery;mySome;myFilter;myReduce

一、myForEach

//myForeach    數組每一個元素都實行一次回調函數
Array.prototype.myForEach = function(callback){
    for(var i = 0 ; i < this.length ; i++){
        var element = this[i];
        callback(element,i,this);
    }
}

二、myEvery

//myEvery    檢測數值元素的每一個元素是不是都相符前提
Array.prototype.myEvery = function(callback){
    for(var i = 0 ; i < this.length ; i++){
        var item = this[i];
        if(!callback(item,i,this)){
            return false;
        }    
    }
    return true;
}

三、mySome

//mySome    檢測數組元素中是不是有元素相符指定前提
Array.prototype.mySome = function(callback){
    for(var i = 0 ; i < this.length ; i++){
        var item = this[i];
        if(callback(item,i,this)){
            return true;
        }
        
    }
    return false;
}

四、myFilter

//myFilter    檢測數值元素,並返回相符前提一切元素的數組
Array.prototype.myFilter = function(callback){
    for(var i = 0 ; i < this.length ; i++){
        var item = this[i];
        if(callback(item,i,this)){
            arr[temp] = item;
            temp++;
        }    
    }
    return arr;
}

五、myReduce

//myReduce    將數組元素盤算為一個值(從左到右)
Array.prototype.myReduce = function(callback,initialValue){
    var num = 0;
    if (initialValue != undefined) {
        total = initialValue;
    }else{
        total = this[0];
        num = 1;
    }

    for(i = num ; i < this.length ; i++){
        var item = this[i];
        total = callback(total,item,i,this);
        
    }
    return total;
}

以上回調函數只是手寫簡化版,沒法傳this參數,若有誤(或發起),請斧正。 ^_^

    原文作者:yuan
    原文地址: https://segmentfault.com/a/1190000014766613
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞