手写各种数组方法

let a = [1, 2, 3];

// 手写map

Array.prototype.myMap = function (fn) {
    let arr = this;
    let res = [];
    for (let i = 0; i < arr.length; i++) {
        res.push(fn(arr[i], i, arr));
    }
    return res;
}
a.myMap((item, index) => {
    console.log(item + 1, index); // 2 0  3 1 4 2
})

// 手写filter

Array.prototype.myFilter = function (fn) {
    let arr = this;
    let res = [];
    for (let i = 0; i < arr.length; i++) {
        if (fn(arr[i], i, arr)) res.push(arr[i]);
    }
    return res;
}
let b = a.myFilter((item, index) => {
    return item > 1;
});
console.log(b); // [ 2, 3 ]

// 手写reduce方法

Array.prototype.myFilter = function (fn,initNum) {
    let arr = this;
    let pre =initNum;
    for (let i = 0; i < arr.length; i++) {
      pre = fn(pre,arr[i],i,arr);
    }
    return pre;
}
let c = a.myFilter((pre,cur) => {
    return pre + cur;
},0);
console.log(c); // 6

// 手写some方法

Array.prototype.mySome = function (fn) {
    let arr = this;
     for (let i = 0; i < arr.length; i++) {
        if (fn(arr[i], i, arr)) return true;
    }
    return false;
}
let d =a.mySome(item => {
    return item > 2;
});
console.log(d); // true

// 手写every方法

Array.prototype.myEvery = function (fn) {
    let arr = this;
     for (let i = 0; i < arr.length; i++) {
        if (!fn(arr[i], i, arr)) return false
    }
    return true;
}
let e =a.myEvery(item => {
    return item > 1;
});
console.log(e); // false

// 手写find方法

Array.prototype.myFind = function (fn) {
    let arr = this;
     for (let i = 0; i < arr.length; i++) {
        if (fn(arr[i], i, arr)) return arr[i];
    }
    return undefined;
}
let f =a.myFind(item => {
    return item > 2;
});
console.log(f); // 3
hxy

hxy

秦 夏

留下你的评论

快留下你的小秘密吧