로그/문제상황
Strange behavior of an array filled by Array.prototype.fill()
차정
2022. 11. 2. 19:07
Strange behavior of an array filled by Array.prototype.fill()
I face something I don't understand with an array. Indeed, I created an array I have filled with empty subArrays to obtain a 2D Matrix. But when I manipulate the array it doesn't behave as I expect...
stackoverflow.com
fill이라는걸 알게됐는데, fill은 primitive 타입에만 써야함.
fill([]) 해버리면 동일한 배열 참조하게해버림
var arr = new Array(5).fill([])
//arr[0] = arr[1] = arr[2] = arr[3] = arr[4] = [];
arr[2].push("third rank item");
console.log(arr);
//[ [ 'third rank item' ],
// [ 'third rank item' ],
// [ 'third rank item' ],
// [ 'third rank item' ],
// [ 'third rank item' ] ]
이렇게 된다는 말임