数组reduce
let arr = [1, 2, 3, 4, 5]
Array.prototype.myReduce = function (fn, initVal) {
for (let i = 0
initVal = fn(initVal, this[i])
}
return initVal
}
let a = arr.myReduce(function (pre, el) {
return pre + el
}, 0)
console.log(a)
数组foreach
let arr = [1, 2, 3, 4, 5]
Array.prototype.myForeach = function (fn) {
for (let i = 0
fn(this[i])
}
}
let a = arr.myForeach(function (el) {
console.log(el)
})
数组map
let arr = [1, 2, 3, 4, 5]
Array.prototype.myMap = function (fn) {
let tempArr = []
for (let i = 0
tempArr.push(fn(this[i]))
}
return tempArr
}
let a = arr.myMap(function (el) {
return (el *= 2)
})
console.log(a)
数组filter
let arr = [1, 2, 3, 4, 5]
Array.prototype.myFilter = function (fn) {
let tempArr = []
for (let i = 0
fn(this[i]) && tempArr.push(this[i])
}
return tempArr
}
let a = arr.myFilter(function (el) {
return el > 2
})
console.log(a)
数组some
let arr = [1, 2, 3, 4, 5]
Array.prototype.mySome = function (fn) {
let res = false
for (let i = 0
if (fn(this[i])) {
res = true
break
}
}
return res
}
let a = arr.mySome(function (el) {
return el > 2
})
console.log(a)
数组every
let arr = [1, 2, 3, 4, 5];
Array.prototype.mySome = function (fn) {
for (let i = 0; i < this.length; i++) {
if (fn(this[i])) {
return true;
}
return false;
}
};
let a = arr.mySome(function (el) {
return el > 0;
});
console.log(a);