如何在JavaScript中形成具有给定宽度(列)和高度(行)的二维数组?

我们需要编写一个包含三个参数的JavaScript函数-

height --> no. of rows of the array
width --> no. of columns of the array
val --> initial value of each element of the array

然后,函数应返回基于这些条件形成的新数组。

示例

为此的代码将是-

const rows = 4, cols = 5, val = 'Example';
const fillArray = (width, height, value) => {
   const arr = Array.apply(null, { length: height }).map(el => {
      return Array.apply(null, { length: width }).map(element => {
         return value;
      });
   });
   return arr;
};
console.log(fillArray(cols, rows, val));

输出结果

控制台中的输出将是-

[
   [ 'Example', 'Example', 'Example', 'Example', 'Example' ],
   [ 'Example', 'Example', 'Example', 'Example', 'Example' ],
   [ 'Example', 'Example', 'Example', 'Example', 'Example' ],
   [ 'Example', 'Example', 'Example', 'Example', 'Example' ]
]