下面我的脚本使用reduce()方法将数组[[0, 1],[2, 3],[4, 5]]
转换为[1, 2, 3, 4, 5]
调试该脚本时,我注意到在Chrome开发工具的作用域选项卡中(请参见下面的屏幕截图),this的值是undefined。你能告诉我为什么吗?我期望这样:窗口。
P.S:我知道有flate()方法,但是我的问题是关于this值。
谢谢你。
const flattened = [
[0, 1],
[2, 3],
[4, 5]
].reduce(
(acc, item) => {
debugger;
return acc.concat(item)
}, []);
您正在使用箭头功能,与正常功能相比有一些区别。箭头函数没有this值。
如果替换箭头功能
(acc, item) => {
具有正常功能,
function (acc, item) {
然后'this'将被设置为'Window'。
-
代码示例和更多信息here:
let user = {
name: "GFG",
gfg1:() => {
console.log("hello " + this.name); // no 'this' binding here
},
gfg2(){
console.log("Welcome to " + this.name); // 'this' binding works here
}
};
user.gfg1();
user.gfg2();
-
编辑:您的代码实际上有效,只是对const本身的赋值没有返回值,因此在控制台上打印“ undefined”。要输出const中的值,只需将其添加到末尾即可:
const flattened = [
[0, 1],
[2, 3],
[4, 5]
].reduce(
(acc, item) => {
return acc.concat(item)
}, []);
flattened
输出:
(6) [0, 1, 2, 3, 4, 5]
由于您在箭头函数中,它将使用词法作用域来确定此值。
[只要我在函数中看到this关键字,这些就是我要找出其引用内容的步骤。取自here。