Unexpected behavior using Array Map on an Array Initialized with Array Fill

前端 未结 1 1350
清歌不尽
清歌不尽 2020-11-27 08:47

I\'ve ran into an issue with the new Array.prototype.fill method due to unexpected output when using it with Array.prototype.map. For example:

相关标签:
1条回答
  • 2020-11-27 09:15

    Your code is equivalent to:

    let inner = Array(3).fill(0);
    let M = Array(3).fill(inner);
    

    When you pass inner to .fill(), it doesn't make copies of it, the M array contains 3 references to the same array. So anything you do to one element of M happens to them all.

    You need to make new arrays for each element of M:

    let M = [];
    for (var i = 0; i < 3; i++) {
        M.push(Array(3).fill(0));
    }
    
    0 讨论(0)
提交回复
热议问题