自定义Js forEach() map()

937 阅读1分钟

自定义forEach

/**
 * forEach的解析
 * 功能:针对每一个元素执行提供的函数
 */

Array.prototype.forEach_m = function (fn, thisArg) {
    for (let i = 0; i < this.length; i++) {
        fn.call(thisArg,this[i], i, this);
    }
}

let arr = [1, 2, 3]
arr.forEach_m((v, i) => {
    console.log(v*2)
})

console.log(arr)

自定义map

/**
 * map函数解析
 * 功能:原数组中的每个元素都按顺序调用一次  callback 函数,callback 每次执行后的返回值(包括 undefined)组合起来形成一个新数组
 */

Array.prototype.map_m = function (fn, thisArg) {
    let arr = []
    for(let i=0; i<this.length; i++) {
        arr.push(fn.call(thisArg, this[i], i))
    }
    return arr
}

let arr = [1, 2, 3, 4, 5]
console.log(arr.map(v=>v*2))
console.log(arr.map_m(v=>v*2))

自定义函数的性能可以查看jspert_ForeachMapMine

区别

  1. forEach不会返回新的数组,而map会根据参数函数返回新的数组。
  2. map:映射
  3. forEach:遍历

使用场景

  1. forEach适合于你并不打算改变数据的时候,而只是想用数据做一些事情。 比如存入数据库或则打印出来。
  2. map()适用于你要改变数据值的时候。map返回一个新的数组。这样的优点在于你可以使用复合(composition)(map(), filter(), reduce()等组合使用)来玩出更多的花样。

如果想要更好的区别,可以参考尤大的如何形象地解释 JavaScript 中 map、foreach、reduce 间的区别? - 尤雨溪的回答 - 知乎 www.zhihu.com/question/24… 的解释 [图片]

【盗个图】: