【问题标题】:Javascript: How to insert a row at an index to a multidimensional array?Javascript:如何在多维数组的索引处插入一行?
【发布时间】:2016-01-20 07:59:46
【问题描述】:

我是 javascript 的新手程序员。请引导我走上正确的道路。

下面是一个大小为 2 x 3 x 3

的 3D 数组
"items": [ [ [1,2,3], [4,5,6], [7,8,9] ], [ [10,11,12], [13,14,15], [16,17,18] ] ]

现在,我需要在索引 1 或 2 处插入一行,例如 [ [19,20,21], [22,23,24], [25,26,27] ]

我尝试了splice 函数,但都是徒劳的。

作为一个多维数组,不知道splice函数的itemN参数是什么值。

items.splice(insertIndex, 0, `????`); 

我该如何完成它?谢谢

【问题讨论】:

    标签: javascript arrays multidimensional-array


    【解决方案1】:

    使用带有 deleteCount 0 的拼接(第二个参数)。作为第三个参数,您输入要添加的二维数组。

    var items = [ [ [1,2,3], [4,5,6], [7,8,9] ], [ [10,11,12], [13,14,15], [16,17,18] ] ];
    var add = [ [19,20,21], [22,23,24], [25,26,27] ];
    items.splice(insertIndex, 0, add);
    

    这里的工作示例:jsfiddle

    【讨论】:

    • 我很困惑。当前的items 数组在索引 1 处已经有值。那么为什么将这个值转移到索引 2 并在索引 1 处添加新值?
    • @HarshMakani - 拼接函数将在指定索引处插入items
    【解决方案2】:

    您可以将要插入的完整数组传递给splice参数,例如:

    items.splice(2, 0,[ [19,20,21], [22,23,24], [25,26,27] ]);
    

    DEMO

    【讨论】:

      【解决方案3】:

      接受的答案很好。

      我做了一个演示,以角度插入中间行作为参考。

      我为谁担心。

          textarray = [
              [{ text: "Content 1" }, { text: "Content 2" }],
              [{ text: "Content 3" }, { text: "Content 4" }]
            ];
            rowindex = 1;
            insertmiddle() {
              let size = this.textarray[0].length;
              this.textarray.splice(this.rowindex, 0, 
                   Array(size).fill({ text: "Content", tag: "Content" }));
            }
      

      https://stackblitz.com/edit/angular-insert-row-matrix

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-27
        • 1970-01-01
        • 1970-01-01
        • 2015-08-11
        相关资源
        最近更新 更多