If we create an array of objects using new Array(l

2020-04-21 02:15发布

问题:

If we create an array of objects using new Array(3).fill({}); and then add any key in any of the objects, it gets reflected in all the 3 objects.

I made an array of objects like: const arr = new Array(3).fill({});

And then I tried doing arr[0][key] = "value"

This updated the key in all 3 objects in the array.

回答1:

You put the same object at 3 different places. It's still the same.

If you want 3 different objects, you may do this for example:

const arr = new Array(3).fill().map(()=>({}));