Array.fill uses the same object for all indices [duplicate]

為{幸葍}努か 提交于 2019-12-13 16:27:05

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/37799249/array-fill-uses-the-same-object-for-all-indices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!