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
版权属于:小小窝/禾下月
本文链接:https://hxyxyz.top/index.php/Web/291.html
本站文章采用 知识共享署名4.0 国际许可协议 进行许可,请在转载时注明出处及本声明!