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

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

问题描述

我正在尝试使用 Array.fill

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

虽然这可行,但问题是内部数组实际上都引用了相同的 Array 对象.

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.

I wanted (and expected) the value of m[1][0] to be 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.from() 代替:

感谢 Pranav C Balan 在评论中对进一步改进这一点的建议.

Thanks to Pranav C Balan in the comments for the suggestion on further improving this.

let m = Array.from({length: 6}, e => Array(12).fill(0));

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

原始声明(上面优化得更好):

Original Statement (Better optimized above):

let m = Array.from({length: 6}, e => Array.from({length: 12}, e => 0));

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

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