问题
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