在 JavaScript 中根据一些约束构造二维数组

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/3 17:16:17

我们需要编写一个 JavaScript 函数,根据一些输入创建一个多维数组。

它应该包含三个元素,即 −

  • row - 数组中存在的子数组的数量,

  • col - 每个子数组中的元素数量,

  • val - 子数组中每个元素的 val,

例如,如果三个输入是 2、3、10

那么输出应该是 −

const output = [[10, 10, 10], [10, 10, 10]];

因此,让我们编写该函数的代码 −

示例

其代码为 −

const row = 2;
const col = 3;
const val = 10;
const constructArray = (row, col, val) => {
   const res = [];
   for(let i = 0; i < row; i++){
      for(let j = 0; j < col; j++){
         if(!res[i]){
            res[i] = [];
         };
         res[i][j] = val;
      };
   };
   return res;
};
console.log(constructArray(row, col, val));

输出

控制台中的输出将是 −

[ [ 10, 10, 10 ], [ 10, 10, 10 ] ]

相关文章


有用资源