Multi-dimension arrays ใช้เมื่อต้องการใส่ arrays ภายใน array ตัวอย่าง อยากเก็บอุณหภูมิทุก 6 ชม. สำหรับทุก weekday อาจทำแบบนี้:
let monday = [35, 28, 29, 31]; let tuesday = [33, 24, 25, 29]; // ...
นี่คือที่เหมาะสำหรับ multidimensional array แทน Multidimensional array คือ array ของ arrays หากนำตัวอย่างต่อไป แต่ละ row แทนวัน แต่ละ entry ใน row แทน temperature entry:
let temps = [ [35, 28, 29, 31], [33, 24, 25, 29] ];
คุณสามารถ chain array access ได้ เช่น ต้องการ element ที่ 3 ใน row ที่ 2 query temps[1][2] สังเกตลำดับคือ rows แล้ว columns สามารถ iterate ด้วย multiple for loops:
let temps = [
[35, 28, 29, 31],
[33, 24, 25, 29]
];
for (let i = 0; i < 2; i++) {
console.log("Row #" + i)
for (let j = 0; j < 4; j++) {
console.log(i, j, temps[i][j])
}
}
ผลลัพธ์:
Row #0 0 0 35 0 1 28 0 2 29 0 3 31 Row #1 1 0 33 1 1 24 1 2 25 1 3 29
Multidimensional arrays สามารถมีมากกว่า 2 dimensions ได้ แต่ 2 dimensions พอสำหรับส่วนใหญ่ ที่ใช้ 3 dimensions เช่น 3D operations, physics calculations ฯลฯ