将值附加到javascript数组

时间:2017-03-02 09:47:19

标签: javascript jquery arrays

如果想要附加到这种类型的数组:

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

3 个答案:

答案 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