在以下 javascript 代码段中,为什么在运行此代码段时元素是 intedious而concise不是等效的?我从第二个元素获得/**ref:2**/输出concise。
const tedious = [
{},
{},
{},
{},
{},
{},
{},
{},
{},
];
const concise = new Array(9).fill({});
console.log(tedious);
console.log(concise);Run Code Online (Sandbox Code Playgroud)
注意:不确定在运行片段时发生了什么,但在现实世界中不会发生引用业务
根据 Xufox 评论:
/**ref:2**/意思是“对数组元素 2 的引用”,因为 Stack Snippets 的控制台功能无法知道你是否有一个无限嵌套的结构,所以取而代之的是 ref 注释(和 id 注释不是在这种情况下使用)被使用
在现实与问题
const concise = new Array(9).fill({});
Run Code Online (Sandbox Code Playgroud)
是所有 9 个条目都将“引用”同一个对象 - 请参阅输出
const concise = new Array(9).fill({});
Run Code Online (Sandbox Code Playgroud)
为了更好地说明这一点,让我们将一个非空对象传递给fill一个随机值
const concise = new Array(9).fill({}); // {}
concise[0].a='hello world';
console.log(JSON.stringify(concise))Run Code Online (Sandbox Code Playgroud)
显然,该对象只创建一次
尝试
const concise = new Array(9).fill({random:Math.floor(Math.random() * 1000)});
console.log(JSON.stringify(concise))Run Code Online (Sandbox Code Playgroud)
由于每个元素都会调用一次 map 回调,因此每次都会创建一个新对象
或者你可以试试
const concise = new Array(9).fill(0).map(() => ({}));
concise[0].a='hello world';
console.log(JSON.stringify(concise))Run Code Online (Sandbox Code Playgroud)
的第二个参数Array.from是一个回调,为每个元素调用一次,基本相同.map
当然,感谢@Slai,以上更简单
const concise = Array.from({length:9}, Object);
Run Code Online (Sandbox Code Playgroud)
将上面“数学随机”代码的输出与
const concise = Array.from({length:9}, () => ({}));
concise[0].a='hello world';
console.log(JSON.stringify(concise))Run Code Online (Sandbox Code Playgroud)