关于javascript:JavaScript中forEach方法的原理和应用

0次阅读

共计 1200 个字符,预计需要花费 3 分钟才能阅读完成。

JavaScript 中 forEach 办法的原理和利用

上一篇文章比照了下 js 中 for 循环和 forEach 办法的区别,明天手写一些 forEach 办法,不便理解的更加粗浅一些。

首先看看 MDN 中 forEach 办法的语法

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

也就是说 forEach 办法传入了一个回调函数,外面第一个参数是以后值,第二个索引,第三个是以后的数组,此外还有一个额定的可选对象,用于指定 callback 办法的 this

首先,咱们测一下 forEach 办法

  const arr2 = ['apply', 'call', 'bind']
  let a = arr2.forEach((item, index) => {console.log(item)
  })
  console.log(a) // undefined
  const arr2 = ['apply', 'call', 'bind']
    var params = {data: 1}
    arr2.forEach(function (item, index) {console.log(this)
      console.log('data', this.data)
    }, {data: 2})
    arr2.forEach((item, index)=> {console.log(this)
      console.log('data', this.data)
    }, {data: 2})
    

强烈建议各位打印一下下面的 console 输入内容

咱们能够看到一些实现时要留神的事项

1、如果应用箭头函数表达式来传入函数参数,thisArg 参数会被疏忽,因为箭头函数在词法上绑定了 this 值。

2、应用一般函数时,第二个参数会当做对应的 this 指向

3、forEach 只是执行回调函数,没有返回值

接下来咱们就能够简略实现下了

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

最重要的是 this 指向这块,好多同学的简略实现都没看语法,不晓得除了函数之外还能够传第二个参数进去。

而且讲真的,callback 中的三个参数,因为第三个是简单对象,所以在 callback 外部扭转了对应数组的话,是会净化原数据的!

不信你试试?

const arr2 = ['apply', 'call', 'bind']
  var params = {data: 1}
  arr2.forEach(function (item, index, arr) {console.log(this)
   console.log('data', this.data)
   arr.push(1)
  }, {data: 2})
  console.log(arr2)

试过的敌人无妨点个赞,哈哈,细还是我细啊!

正文完
 0