首页 > 解决方案 > 使用 Array.fill() 在没有引用的情况下在一行中声明 ES6 多个变量会导致问题

问题描述

据我所知,如果我们使用 创建多个变量Array().fill(),它将创建唯一变量而没有任何引用。下面是两个代码块和输出。

let [a, b] = Array(2).fill(false);
console.log(a, b); // Output: false false
a = true;
console.log(a, b); // Output: true false

let [x, y] = Array(2).fill([]);
console.log(x, y); // Output:[] []
x.push(1);
console.log(x, y); // Output:[1] [1]

第一个代码块没问题,没有参考。但是第二个会发生什么。我期待输出“[1] []”。请澄清这里发生了什么。

标签: javascriptecmascript-6

解决方案


推荐阅读