如何在 JavaScript 中形成具有给定宽度(列)和高度(行)的二维数组?
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个接受三个参数 − 的 JavaScript 函数
height --> 数组的行数 width --> 数组的列数 val --> 数组每个元素的初始值
然后,该函数应返回基于这些条件形成的新数组。
示例
其代码为 −
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' ] ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

