javascript - 如何以编程方式创建和填充数组
问题描述
我正在尝试以编程方式创建一个多维数组。但是当我将一个对象推入数组时,它会被推入数组中的所有索引中。为什么会这样
这是一个简单的演示
let postTest = new Array(4).fill([]);
postTest[0].push({key: 'value', anotherKey: 'value'});
console.log(postTest);
解决方案
Array.from
改为使用,Array.prototype.fill
将对象的引用复制到所有位置,以便一个位置的任何更改都会反映在所有位置
let postTest = Array.from({length: 4}, ()=> []);
postTest[0].push({ key: 'value', anotherKey: 'value' });
console.log(postTest);
推荐阅读
- sql - 使用 memdb 和 dbplyr 设置覆盖 == TRUE
- javascript - 如何在正则表达式中指定拆分:2个双引号内除外
- c# - 反序列化嵌套的 Json C#
- mysql - 在 bash 脚本中设置环境或全局变量
- python - 在
: TypeError: 类型对象有多个关键字参数值 - python - 未解决的参考 flask_sqlalchemy
- ionic-framework - Ionic facebook登录:获取此应用程序仍处于开发模式而我将其设置为实时模式
- c++ - GTK 进度条的使用
- service-worker - 默认cache.addAll缓存时间?
- python - 使用 Pandas + xlsxwriter 删除索引的边框