gpt4 book ai didi

javascript - 如何动态地向对象添加数组?

转载 作者:行者123 更新时间:2023-12-04 01:17:59 24 4
gpt4 key购买 nike

我要达到的目的

我试图动态地将数组添加到对象。也就是说,从

 {colour: "white", type: "electric"};

并以
{colour: "white", type: "electric", owners: ["person1", "person2", "person3"] };

请考虑以下对象
let car = {colour: "white", type: "electric"};

如果要向该对象添加另一个属性,则可以检查它是否存在。然后添加如下。
if( typeof car.status === "undefined")
car.status = "sold";

我尝试了什么

使用以上逻辑,我尝试了以下操作

let car = {
colour: "white",
type: "electric"
};

if (typeof car.owners === "undefined")
car.owners.push("person1");


但这不起作用。

问题

如何将数组添加到对象?

最佳答案

要将数组添加到对象,请创建该数组并将其分配给属性:

let car = {
colour: "white",
type: "electric"
};

if (typeof car.owners === "undefined") {
// vvvvvvvvvvv----- creates the array
car.owners = ["person1"];
// ^^^^^^^^^--- assigns it to the property
}

console.log(car);


如果要稍后添加到该数组,则可以使用 push。但是数组必须首先存在。例如:
// `person` has the person to add...
if (typeof car.owners === "undefined") {
car.owners = [person];
} else {
car.owners.push(person);
}

也就是说,最好避免不必要地更改对象的形状。我只是从一个空数组开始,然后删除 if:

let car = {
colour: "white",
type: "electric",
owners: [] // <=== Empty array
};

car.owners.push("person1");

console.log(car);

关于javascript - 如何动态地向对象添加数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59693812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com