如何在 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' ]
]

更新日期: 20-11-2020

358 瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.