javascript - 从现有数组创建动态数组?
问题描述
所以我正在尝试从现有的数组中创建新数组。所以基本上我有一个结构如下所示的数组。我怎样才能做到这一点,如果我要添加一个新对象,从那时起会产生一个新数组?
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' }
]
如果我要在原始数组中添加新对象,那最终会出现在新数组中。希望我已经尽我所能解释了它。
解决方案
使用扩展运算符轻松地从现有数组创建非引用数组。
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]
推荐阅读
- javascript - 打字稿承诺导致代码静默崩溃
- c - GetMessageW 正在阻塞调用线程,没有收到任何消息
- c++ - 使用 memcpy 从二维数组中复制一系列元素
- r - 无法为 R 中的列表替换 NA 的错字
- oauth-2.0 - AAD v2.0:无法将 .default 范围与设备代码流一起使用
- java - Java OverlayLayout 项目排列问题
- c++ - C++:如何在可变参数模板参数上调用具有类型参数的函数?
- javascript - 使用 JS 从文本文件中检索随机选择的数据
- android - Firebase 身份验证 UI - 提示颜色 (Android)
- java - 在 Apache Poi Powerpoint 形状中设置线连接样式