【问题标题】:JavaScript Array.push() duplicating across multiple (nested) arrays [duplicate]JavaScript Array.push() 跨多个(嵌套)数组复制 [重复]
【发布时间】:2021-07-11 15:02:29
【问题描述】:

最近,我试图创建三层深嵌套数组。疯了,我知道,但这是我能想到的解决我问题的最佳方法。使用以下代码创建数组。

const lengths = [2, 3];

const arrays = lengths.map((v, i) => {
    return Array(lengths[i]).fill([]);
});

arrays[0][0].push(1);

console.log(arrays);
// Expected: [ [ [ 1 ], [] ], [ [], [], [] ] ]
// Actual: [ [ [ 1 ], [ 1 ] ], [ [], [], [] ] ]

如您所见,我只推送到数组[0][0]。然而,[0][0] 和 [0][1] 都被推送到。这里发生了什么?它是一个错误,还是一个功能?某种奇怪的内存管理?

如果有帮助,我正在使用 Node.js。提前致谢。

【问题讨论】:

    标签: javascript node.js arrays multidimensional-array


    【解决方案1】:

    您正在使用相同的数组引用填充整个数组。相反,您可以使用Array.from 的映射回调来纠正此问题,每次返回不同的数组。

    const lengths = [2, 3];
    
    const arrays = lengths.map((v, i) => {
        return Array.from({length: lengths[i]}, _=>[]);
    });
    
    arrays[0][0].push(1);
    
    console.log(arrays);
    .as-console-wrapper{top:0;max-height:100%!important}

    【讨论】:

      猜你喜欢
      • 2015-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多