如何在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' ] ]
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短