TypeScript遍历字符串数组为关联数组加新键遇问题求助
问题核心原因:普通函数与箭头函数的this绑定差异
如果你的代码是在类的方法、对象方法或其他依赖特定this的上下文中运行,普通function作为forEach回调时会改变this的指向,而箭头函数会继承外部作用域的this,这就是两种写法表现不同的关键。
举个你大概率遇到的场景:假设secondArray是类的实例属性,代码结构类似这样:
class MyClass { secondArray: Record<string, boolean> = {}; init() { const firstArray = ["KeyOne", "KeyTwo", "KeyThree"]; this.secondArray["InitialKey"] = true; // 普通function写法:此时this不是MyClass的实例 firstArray.forEach(function(value) { // 非严格模式下this指向全局对象,严格模式下为undefined,this.secondArray不存在 this.secondArray[value] = false; }); // 箭头函数写法:继承外层init方法的this(即MyClass实例) firstArray.forEach(value => { this.secondArray[value] = false; // 正确访问实例属性,添加键值对 }); } }
这种情况下,普通函数回调里的this指向错误,导致无法正确访问secondArray;而箭头函数保留了外部的this,所以能正常为对象添加键。
如果secondArray是局部变量
如果你的代码和贴出来的一致(secondArray是局部变量),理论上普通函数也能正常访问。若还是失效,检查这两点:
- 是否在普通函数回调内部重新声明了
secondArray(比如写了let secondArray;),导致遮蔽了外部变量; - 是否开启了TypeScript严格模式,
this绑定问题间接干扰了变量查找(这种情况很少见)。
额外解决方法:手动指定回调的this
你也可以用普通函数,通过forEach的第二个参数指定回调的this,同样能解决问题:
const firstArray = ["KeyOne", "KeyTwo", "KeyThree"]; const secondArray = {}; secondArray["InitialKey"] = true; // 第二个参数把回调的this绑定为secondArray firstArray.forEach(function(value) { this[value] = false; }, secondArray);
内容的提问来源于stack exchange,提问作者Oliver
相关产品推荐
相关产品推荐

