手写foreach、filter、map、every、some函数
作者:互联网
1.foreach实现原理
function foreach(array, fn) {
for (i = 0; i < array.length; i++) {
fn(array[i])
}
}
// 测试
let arr = [1,2,5,6,7,8];
foreach(arr,function(item){
console.log(item)
})
2.filter实现原理
function filter(array, fn) {
let results = []
for (i = 0; i < array.length; i++) {
if (fn(array[i])) {
results.push(array[i])
}
}
return results;
}
// 测试 过滤偶数
let arr = [1, 2, 5, 6, 7, 8];
let r = filter(arr, function (item) {
return item % 2 === 0
})
console.log(r)
3.map实现原理
const map = (array,fn)=>{
let results = []
for(let value of array){
results.push(fn(value))
}
return results;
}
// 测试
let arr = [1,2,3,4,5]
let r = map(arr,v=>v*v)
console.log(r)
4.every实现原理
const every = (array, fn) => {
let result = true
for (let value of array) {
result = fn(value)
if (!result) {
break
}
}
return result;
}
// 测试
let arr = [1, 2, 3, 4, 5]
let r = every(arr, v => v > 0)
console.log(r)
5.some实现原理
const some = (array, fn) => {
let result = true
for (let value of array) {
result = fn(value)
if (result) {
break
}
}
return result;
}
// 测试
let arr = [2, 3, 4, 5, 6, 1]
let r = some(arr, v => v % 2 === 0)
console.log("输出结果:"+r)
以上函数主要利用了函数可以作为参数这一特性来实现的。
标签:map,arr,some,results,filter,let,result,array,fn 来源: https://www.cnblogs.com/ma1998/p/16369308.html