首页 > 解决方案 > 从现有数组创建动态数组?

问题描述

所以我正在尝试从现有的数组中创建新数组。所以基本上我有一个结构如下所示的数组。我怎样才能做到这一点,如果我要添加一个新对象,从那时起会产生一个新数组?

myArray: [{
    animal: 'cat',
    food: 'cupcake'
  },
  {
    animal: 'dog',
    food: 'pizza'
  },
  {
    animal: 'lion',
    food: 'apple'
  },
  {
    animal: 'elephant',
    food: 'spinach'
  },
]

因此,如果我要添加一个新对象{ animal: 'rhino', food: 'banana'},结果将生成一个新数组,所以它会是这样的:

newArray: [
   { animal: 'rhino', food: 'banana' }
  ]

如果我要在原始数组中添加新对象,那最终会出现在新数组中。希望我已经尽我所能解释了它。

标签: javascriptarrays

解决方案


使用扩展运算符轻松地从现有数组创建非引用数组。

const myArray = [1, 2, 3] //original array
const myArray2 = [...myArray] //spread operator to create non-referencing array
myArray2.push(4)
console.log(myArray) // [1, 2, 3]
console.log(myArray2) // [1, 2, 3, 4]

推荐阅读