首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >数组内的JS数组-添加一个新的“迷你数组”

数组内的JS数组-添加一个新的“迷你数组”
EN

Stack Overflow用户
提问于 2020-12-18 23:23:09
回答 4查看 57关注 0票数 1

在数组中添加元素嵌入数组- Javascript我有以下数组:

代码语言:javascript
代码运行次数:0
运行
复制
[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

,并且在该数组中,其中的每个数组看起来如下所示:

代码语言:javascript
代码运行次数:0
运行
复制
0 : {_id: "bla", header: "test", time: "test PM", content: "test", uniqueid: "test"}
    1: {_id: "blay", header: "tests", time: "tests PM", content: "even more tests", uniqueid: "tests"}
    2: {_id: "awa", header: "sd", time: 3:14:15 PM", content: "sdf", uniqueid: "sdfg"}

我的问题是,我如何在这个大数组中插入另一个“小数组”,在位置0,header: finaltest,time: finalTest PM,content: thefinaltest和唯一I: testt?

我在想也许可以使用.unshift,但我不确定。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2020-12-18 23:35:33

嗨,你是说像这样的东西吗?

代码语言:javascript
代码运行次数:0
运行
复制
let table = [
  {_id: "bla", header: "test", time: "test PM", content: "test", uniqueid: "test"},
  {_id: "blay", header: "tests", time: "tests PM", content: "even more tests", uniqueid: "tests"},
  {_id: "awa", header: "sd", time: "3:14:15 PM", content: "sdf", uniqueid: "sdfg"}
   ]


let newRow = {_id: "bl@@@@", header: "finaltest", time: "finalTest PM", content: "test", uniqueid: "testt"};

table.unshift(newRow);


console.log(table);
票数 1
EN

Stack Overflow用户

发布于 2020-12-18 23:33:29

如果你想创建一个新的数组,而不是改变现有的数组,你可以使用扩展运算符:

代码语言:javascript
代码运行次数:0
运行
复制
const originalArray = [{}, {}, {}, {}]
const newObj = { some: 'values' }

const newArray = [newObj, ...originalArray]

结果:

代码语言:javascript
代码运行次数:0
运行
复制
// newArray
[{ some: 'values' }, {}, {}, {}, {}]
票数 1
EN

Stack Overflow用户

发布于 2020-12-18 23:35:52

Javascript的splice()方法可以提供帮助。就这么简单:

代码语言:javascript
代码运行次数:0
运行
复制
const data = [
    { _id: "bla", header: "test", time: "test PM", content: "test", uniqueid: "test" },
    { _id: "blay", header: "tests", time: "tests PM", content: "even more tests", uniqueid: "tests" },
    { _id: "awa", header: "sd", time: "3:15 PM", content: "sdf", uniqueid: "sdfg" }
];

const inserted_obj = { _id: "inserted", header: "finaltest", time: "finalTest PM", content: "thefinaltest", uniqueid: "testt" };

let start = 0;
let deleteCount = 0;
data.splice(start, deleteCount, inserted_obj);
console.log(data);

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65359611

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档