学无先后,达者为师

网站首页 前端文档 正文

javaScript中forEach循环改变this指向

作者:Wxinin 更新时间: 2022-04-23 前端文档
function foo(el) { 
console.log(el,this.id)
 }
var obj = { 
 id:'小明'
  }
var nums = [1,2,3] 
nums.forEach(foo,obj)

输出的结果为
在这里插入图片描述

值的注意的是forEach循环数组的参数有两个一个是回调函数,另一个是this的指向

thisValue 可选。传递给函数的值一般用 “this” 值。
如果这个参数为空, “undefined” 会传递给 “this” 值里是引用

array.forEach(function(currentValue, index, arr), thisValue)

原文链接:https://blog.csdn.net/weixin_44283589/article/details/123175203

栏目分类
最近更新