我们需要编写一个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 ] ]




