【问题标题】:JS array inside an array - Adding a new "mini-array"数组中的 JS 数组 - 添加新的“迷你数组”
【发布时间】:2021-03-29 06:13:44
【问题描述】:

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

[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

,在那个数组中,里面的每个数组都是这样的:

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,标题:finaltest,时间:finalTest PM,内容:thefinaltest,uniqueid:testt?

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

【问题讨论】:

标签: javascript html node.js arrays multidimensional-array


【解决方案1】:

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

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);

【讨论】:

    【解决方案2】:

    您好,您的意思是这样的吗?

    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);
    

    【讨论】:

      【解决方案3】:

      使用Array.unshift() 似乎是将其添加到 0 位置的方法。

      如果要将其添加到数组的末尾,请使用Array.push()

      要将其添加到特定位置,Array.splice() 会起作用。

      您可以将任何数据类型添加到数组中,因此在另一个数组中插入一个数组不是问题。

      【讨论】:

        【解决方案4】:

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

        const originalArray = [{}, {}, {}, {}]
        const newObj = { some: 'values' }
        
        const newArray = [newObj, ...originalArray]
        

        结果:

        // newArray
        [{ some: 'values' }, {}, {}, {}, {}]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-10-19
          • 2023-03-28
          • 1970-01-01
          • 2015-04-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多