向数组添加新对象

时间:2019-04-15 21:22:49

标签: javascript arrays methods

此函数通过向其添加一个新对象来更改我的数组(第二个参数中传递了一个新对象)。我可以使用什么方法返回新数组,而不更改旧数组?

sanitization

3 个答案:

答案 0 :(得分:2)

您可以使用Array.concat()spread syntax

function pushArr(arr, item) {
  return arr.concat(item); // or return [...arr, item]
}

const arr = [{"name":"BMW","price":"55 000","country":"Germany","certificate":"yes"},{"name":"Mitsubishi","price":"93 000","constructor":"Bar John","door":"3","country":"Japan"},{"name":"TOYOTA","price":"48 000","max_people":"7","country":"Japan","certificate":"yes"},{"name":"Volkswagen","price":"36 000","constructor":"Pier Sun","country":"Germany","certificate":"no"}];

let Cars = pushArr(arr, {
  "name": "Audi",
  "price": "89 000",
  "constructor": "Adolf Trump",
  "country": "Germany",
  "certificate": "yes"
});

console.log(arr === Cars);
console.log(Cars);

答案 1 :(得分:1)

这是因为JavaScript对象(包括数组)是通过引用传递的,而标量值是通过值传递的。

因此,当您将对象传递给函数并直接对其进行突变时,实际上是在引用内存中的同一对象。

为避免意外更改对象,您必须在执行对象操作之前创建该对象的新实例。有多种方法可以做到这一点:

const arr = [{
    "name": "BMW",
    "price": "55 000",
    "country": "Germany",
    "certificate": "yes"
  },
  {
    "name": "Mitsubishi",
    "price": "93 000",
    "constructor": "Bar John",
    "door": "3",
    "country": "Japan",
  },
  {
    "name": "TOYOTA",
    "price": "48 000",
    "max_people": "7",
    "country": "Japan",
    "certificate": "yes"
  },
  {
    "name": "Volkswagen",
    "price": "36 000",
    "constructor": "Pier Sun",
    "country": "Germany",
    "certificate": "no"
  },
];

//destructure your argument here 
function pushArr([...arr], item) {
  return [arr, item];
}

let Cars = pushArr(arr, {
  "name": "Audi",
  "price": "89 000",
  "constructor": "Adolf Trump",
  "country": "Germany",
  "certificate": "yes"
});

console.log(arr);
console.log(Cars);

值得注意的是,重新分配对象不会更新该值。请查看Call by sharing

答案 2 :(得分:1)

您可以使用函数slice创建副本。

function pushArr(arr, item) {
    let copy = arr.slice();
    copy.push(item);
    return copy;
}