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)
试过的敌人无妨点个赞,哈哈,细还是我细啊!