首页 > 解决方案 > 如何以编程方式创建和填充数组

问题描述

我正在尝试以编程方式创建一个多维数组。但是当我将一个对象推入数组时,它会被推入数组中的所有索引中。为什么会这样

这是一个简单的演示

let postTest = new Array(4).fill([]);
postTest[0].push({key: 'value', anotherKey: 'value'});
console.log(postTest);

标签: javascript

解决方案


Array.from改为使用,Array.prototype.fill将对象的引用复制到所有位置,以便一个位置的任何更改都会反映在所有位置

let postTest = Array.from({length: 4}, ()=> []);

postTest[0].push({ key: 'value',  anotherKey: 'value' });

console.log(postTest);


推荐阅读