如何在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 20岁简短生日祝福语
14 祝老婆生日祝福语简短
15 拥有爱的祝福语简短
16 早日回国祝福语简短英语
17 祝寿时祝福语简短精辟
18 简短霸气的考试祝福语