Skip to content

13. forEach和map的区别

两个的作用都是遍历数组,主要区别就是map会返回一个新数组,而forEach不会

map

js
  // 简单手写
  Array.prototype.myMap(callback) {
    let newArr = []
    for(let i = 0; i< this.length ; i++) {
      newArr.push(callback(this[i], i, this))
    }
    return newArr
  }

forEach

js
  // 简单手写
  Array.prototype.myForEach(callback) {
    for(let i = 0;i < this.length; i++) {
      callback(this[i], i , this)
    }
  }

两者都不会修改原数组

KESHAOYE-知识星球