如果想要附加到这种类型的数组:
array = ["one","two","three"];
所以它变成了,
array = ["one","two","three, "four"];
使用:
array.push("four");
但是你如何追加到这里:
object = {element1: one, element2: two, array: ["one","two","three"]};
所以它变成了,
object = {element1: one, element2: two, array: ["one","two","three,"four"]};
答案 0 :(得分:6)
您仍然使用push()
,但在对象的array
属性中:
var obj = {
element1: 1,
element2: 2,
array: ["one", "two", "three"]
};
obj.array.push('four');
console.log(obj);

答案 1 :(得分:3)
您可以像这样更新对象:
let obj = {element1: 'one', element2: 'two', array: ["one","two","three"]};
obj.array.push('four');
如果要使用扩展阵列创建对象的新副本,还可以使用新的ES6功能执行以下操作:
let obj = {element1: 'one', element2: 'two', array: ["one","two","three"]};
let newObject = Object.assign({}, obj, { array: [...obj.array, 'four'] });
使用第二个示例,保持原始对象不变,并使用更新的值创建新副本。
答案 2 :(得分:1)
在您的情况下,值one, two
必须是字符串,否则它们将被视为变量,并且您也可以使用push
object.array.push('four');
来使用var object = {
element1: "one",
element2: "two",
array: ["one", "two", "three"]
};
object.array.push('four');
console.log(object);
:
assert_receive