I don't quite understand the extension of the fill method of the Array object, so the result of this code is a little confusing.

var arr = Array(3).fill({}) // [{}, {}, {}];
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]

it can be understood that the first line of the function fill (), populating array elements fills an array of three elements with empty objects.
the second line assigns the first element {hi: "hi"}

.

Why does the array end up with all elements {hi: "hi"}?

Mar.15,2021

because they are all assigned to the same {} , that is, all three elements of the array point to the same reference.

Menu