数组中。fill所有索引都使用相同的对象[duplicate]

时间:2023-02-09 20:17:38

This question already has an answer here:

这个问题已经有了答案:

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?

这有道理吗?

2 个解决方案

#1


3  

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.

您正在将引用传递给已创建的对象实例。如果您首先声明数组(如。var c =[])然后用它填充arr,你会得到相同的行为。

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"]]

#2


1  

Yes, it does make sense.

是的,这是有道理的。

fill expects a value that is put in all the indices, not a function that produces a new value for every index. And it doesn't implicitly clone the value you passed either (no standard function does that). This is just the usual assignment behaviour, wherein objects (reference values) stay the same.

fill期望在所有索引中放入一个值,而不是为每个索引生成一个新值的函数。它也不会隐式地克隆您传递的值(没有任何标准函数会这样做)。这只是通常的赋值行为,其中对象(引用值)保持不变。

#1


3  

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.

您正在将引用传递给已创建的对象实例。如果您首先声明数组(如。var c =[])然后用它填充arr,你会得到相同的行为。

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"]]

#2


1  

Yes, it does make sense.

是的,这是有道理的。

fill expects a value that is put in all the indices, not a function that produces a new value for every index. And it doesn't implicitly clone the value you passed either (no standard function does that). This is just the usual assignment behaviour, wherein objects (reference values) stay the same.

fill期望在所有索引中放入一个值,而不是为每个索引生成一个新值的函数。它也不会隐式地克隆您传递的值(没有任何标准函数会这样做)。这只是通常的赋值行为,其中对象(引用值)保持不变。