You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整多维数组尺寸以添加空行与空列?

如何向多维数组中添加空列与空行?

先看给定的示例数组:

// (1s 只是任意数据的占位符)
let arr = [ 
     [1,1,1,1],
     [1,1,1,1],
     [1,1,1,1],
    ];

我们需要给它添加3个空列和2个空行,最终得到目标数组:

let result = [ 
      [1,1,1,1,"","",""],
      [1,1,1,1,"","",""],
      [1,1,1,1,"","",""],
      ["","","","","","",""],
      ["","","","","","",""],
     ];

实现步骤

1. 添加空列

遍历原数组的每一行,给每行末尾追加指定数量的空字符串即可。比如要加3个空列,可以用Array.fill()生成包含3个空字符串的数组,再和原行合并:

// 添加3个空列
const columnsToAdd = 3;
const arrWithColumns = arr.map(row => {
  return [...row, ...Array(columnsToAdd).fill("")];
});

2. 添加空行

先确定添加列后每行的长度,然后生成对应长度的空行(每个元素都是空字符串),再把这些空行追加到数组末尾:

// 添加2个空行
const rowsToAdd = 2;
const rowLength = arrWithColumns[0].length;
const arrWithRows = [...arrWithColumns, ...Array(rowsToAdd).fill(Array(rowLength).fill(""))];

完整代码

把两步合并起来就是完整的实现:

let arr = [ 
     [1,1,1,1],
     [1,1,1,1],
     [1,1,1,1],
    ];

const columnsToAdd = 3;
const rowsToAdd = 2;

// 先加空列
const arrWithColumns = arr.map(row => [...row, ...Array(columnsToAdd).fill("")]);

// 再加空行
const rowLength = arrWithColumns[0].length;
const result = [...arrWithColumns, ...Array(rowsToAdd).fill(Array(rowLength).fill(""))];

console.log(result);

内容的提问来源于stack exchange,提问作者Einarr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:42:47