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

สร้างอาร์เรย์ 2 มิติ ตามเงื่อนไข Row, Col, Value - JavaScript

สร้างอาร์เรย์ 2 มิติ (Matrix) ขนาด Row × Col เติมค่า Value เดียวกันทุกเซลล์

ตัวอย่าง

row=2, col=3, val=10 → [[10,10,10], [10,10,10]]

ตัวอย่างโค้ด

const constructArray = (row, col, val) => 
  Array.from({ length: row }, () => Array(col).fill(val));

console.log(constructArray(2, 3, 10));

ผลลัพธ์

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

วิธีแบบ Loop (Classic)

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

Array.from({length}, mapFn) สร้างอาร์เรย์ขนาดกำหนด เรียก mapFn ทุก Index