Array.fill(Array)通过引用而不是按值创建副本 [英] Array.fill(Array) creates copies by references not by value

查看:140
本文介绍了Array.fill(Array)通过引用而不是按值创建副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Array.fill

let m = Array(6).fill(Array(12).fill(0));

虽然这样工作,但问题是内部数组实际上都引用了相同的 array object。

While this works, the problem is that the inner Arrays are actually all referencing the same Array object.

let m = Array(6).fill(Array(12).fill(0));
m[0][0] = 1;
console.log(m[1][0]); // Outputs 1 instead of 0

我想(和预期) m [1] [0] 0

强制 Array.fill 填充给定参数的副作用(例如: Array(12).fill(0)是我的例子),而不是通过引用复制?

How can I force Array.fill fill copy-by-values of the given argument (eg: Array(12).fill(0) is the argument in my case) instead of copying by reference ?

推荐答案

你不能用 Array#fill 方法。相反,迭代数组,并使用for循环添加新创建的数组。

You can't do it with Array#fill method. Instead iterate over the array and add newly created array using a for loop.

let m = Array(6);
for (var i = 0; i < m.length; i++)
  m[i] = Array(12).fill(0)

m[0][0] = 1;
console.log(m[1][0]);

这篇关于Array.fill(Array)通过引用而不是按值创建副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆