Array.fill对所有索引使用相同的对象 [英] Array.fill uses the same object for all indices
本文介绍了Array.fill对所有索引使用相同的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
const arr = Array(2).fill([]);
arr [0] .push('a');
arr [1] .push('b');
// [['a','b'],['a','b']]
我一直在阅读一些文档,但我没有看到任何地方提到这种行为。
这是否有意义?
解决方案
是的。
您正在传递对创建的对象实例的引用。
如果您首先声明数组(例如 var c = []
),然后填入 arr
你会得到相同的行为。
const c = [];
const arr = Array(2).fill(c);
c.push(a);
c.push(b);
// c [a,b]
// arr [引用c,引用c] => [[a,b],[a,b]]
I'm using Array.fill to prepopulate an array with other arrays. Modifying the array of one indices also modifies the array of another. Meaning its the same object.
const arr = Array(2).fill([]);
arr[0].push('a');
arr[1].push('b');
// [['a', 'b'], ['a', 'b']]
I've been reading through some documentation but I don't see this behavior mentioned anywhere. Same thing happens with an object literal.
Does this make sense somehow?
解决方案
Yes it does.
You are passing a reference to an created object instance.
If you would first declare the array (eg. var c = []
) and then populate arr
with it you would get the same behavior.
const c = [];
const arr = Array(2).fill(c);
c.push("a");
c.push("b");
// c ["a", "b"]
// arr [reference to c, reference to c] => [["a","b"], ["a", "b"]]
这篇关于Array.fill对所有索引使用相同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文