首页 > 解决方案 > 如何为 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

所以,我的问题是:

标签: javascriptarraysobject

解决方案


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; }


推荐阅读