javascript – array.forEach的thisArg没有按预期引用
作者:互联网
给出以下代码:
const theArray = ['Audi','Volvo','Mercedes'];
const myObj = {a: 7};
theArray.forEach((value, index, array) => {
console.log(index + ' : ' + value);
console.log(array === theArray);
console.log(this.a);
}, myObj);
我得到以下输出:
0 : Audi
true
undefined
1 : Volvo
true
undefined
2 : Mercedes
true
undefined
我不明白为什么这不引用myObj并返回undefined而不是7.
虽然这个类型的Object返回true,但我不知道它引用了哪个Object.我只知道这会返回一个空对象(即.{})
Node.js解释器版本是v6.2.1
V8-Engine版本为5.0.71.52
解决方法:
问题
An arrow function expression has a shorter syntax compared to 07001 and lexically binds the 07002 value (does not bind its own 07002, 07004, 07005, or 07006). Arrow functions are always 07007.
解决方案1
使用功能
const theArray = ['Audi','Volvo','Mercedes'];
const myObj = {a: 7};
theArray.forEach(function (value, index, array) {
console.log(index + ' : ' + value);
console.log(array === theArray);
console.log(this.a);
}, myObj);
解决方案2
使用封闭物
var abc = 'abc';
const theArray = ['Audi','Volvo','Mercedes'];
const myObj = {a: 7};
theArray.forEach((obj => (value, index, array) => {
console.log(index + ' : ' + value);
console.log(array === theArray);
console.log(obj.a);
console.log(this.abc);
})(myObj));
标签:object-reference,javascript,node-js,foreach 来源: https://codeday.me/bug/20190727/1554657.html