javascript - 如何为 JavaScript 中对象数组中特定元素的属性赋值?
问题描述
我有一个对象数组,并使用Array.prototype.fill()
. 我想为数组中特定元素的属性分配一个新值。
例如:
let data = Array(3).fill({test_1: 0, test_2: true});
function f(index) {
data[index].test_1 = 5;
console.log(data);
}
f(0);
但是,不是将该值分配给该特定对象的属性,而是数组中的所有对象都有自己的属性分配相同的值。
这是输出:
// Actual result
[
{
test_1: 5,
test_2: true
},
{
test_1: 5,
test_2: true
},
{
test_1: 5,
test_2: true
}
];
// Expected result
[
{
test_1: 5,
test_2: true
},
{
test_1: 0,
test_2: true
},
{
test_1: 0,
test_2: true
}
];
不是只有第一个对象的test_1
属性值是 5,而是所有三个对象的属性值都是 5 test_1
。
所以,我的问题是:
- 为什么
f()
将相同的值分配给数组中所有元素的相同属性? - 如何将值分配给仅数组特定元素的属性?
解决方案
Array.fill
除非你想用原始类型填充它,否则不要使用。
这样let data = Array(3).fill({test_1: 0, test_2: true})
,您每次都传递相同的对象,因此您的数组包含 3 次相同的对象,那么如果您修改数组的任何元素,实际上它是通过引用修改的同一个对象。为避免它使用Array.from
结合地图回调的语法。像这样:
let data = Array.from({length: 3}, _ => ({test_1: 0, test_2: true}))
function f(index) {
data[index].test_1 = 5;
console.log(data);
}
f(0)
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- jenkins - Jenkins 在 `'docker' 上构建摊位正在等待`
- python - 如何从不同的子域引用 create_app?
- google-sheets - 将值隔离到单元格中的第六个“/”的最佳方法(Google 表格)
- css - 如何仅在 CSS 更改期间构建 CSS/PostCSS?
- python - python selenium 说 xpath 表达式无效
- python - 定义 numpy 索引数组
- swift - 将 Swift 结构定义移动到不同的文件会导致构建失败
- html - 如何在响应式 CSS 按钮中对齐文本中心?
- terraform - 获取 AWS CloudWatch 警报的 terraform 参考
- c# - 跨不同 Windows 机器的 MDF 数据库文件的可移植性