Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

สร้างอาร์เรย์ 2 มิติด้วยความกว้างและความสูงที่กำหนด - JavaScript

เราต้องเขียนฟังก์ชัน JavaScript ที่สร้างอาร์เรย์หลายมิติจากอินพุต 3 ค่า ได้แก่:

  • row - จำนวน subarray ในอาร์เรย์
  • col - จำนวนสมาชิกในแต่ละ subarray
  • val - ค่าของแต่ละสมาชิกใน subarray

เช่น หากอินพุตคือ 2, 3, 10 ผลลัพธ์ควรเป็น:

const output = [[10, 10, 10], [10, 10, 10]];

ตัวอย่าง

โค้ดต่อไปนี้เป็นตัวอย่าง:

const row = 2;
const col = 3;
const val = 10;

const constructArray = (row, col, val) => {
  const res = [];
  for(let i = 0; i < row; i++){
    for(let j = 0; j < col; j++){
      if(!res[i]){
        res[i] = [];
      };
      res[i][j] = val;
    };
  };
  return res;
};

console.log(constructArray(row, col, val));

ผลลัพธ์

จะแสดงผลในคอนโซลดังนี้:

[ [ 10, 10, 10 ], [ 10, 10, 10 ] ]