如何在 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' ] ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP