1. 程式人生 > 其它 >手寫陣列方法

手寫陣列方法

reduce

Array.prototype.myReduce = function(fn,initVal){
    if(typeof fn !== 'function'){
        throw Error('Type Error')
    }

    const arr = this;
    if(arguments.length < 2 && arr.length === 0){
        throw new TypeError('Reduce of empty array with no initial value')
    }

    let res;
    let index;
    if(arguments.length > 1){
        res = initVal;
        index = 0;
    } else{
        res = arr[0];
        index = 1;
    }
    for(let i = index; i < arr.length; i++){
        res = fn(res,arr[i],i,arr);
    }
    return res;
}

const arr = [1,2,3];

const res = arr.myReduce((pre,cur,index,arr) => {
    console.log('pre',pre,'cur',cur,'index',index)
    console.log('arr',arr)
    return pre + cur
})

map

Array.prototype.myMap = function(fn){
    if(typeof fn !== 'function'){
        throw Error('Type Error')
    }

    const arr = this;
    const newArr = [];
    for(let i = 0; i < arr.length; i++){
        newArr.push(fn(arr[i], i));
    }
    return newArr;
}

const arr = [1];

const res = arr.myMap((item,index) => {

    return item + index;
})
console.log(res)