Indexed Collections คือโครงสร้างข้อมูลที่เข้าถึง Element ผ่าน Index (Integer) โดย Array เป็น Indexed Collection หลักของ JavaScript
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Indexed Collections</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; color: blueviolet; }
</style>
</head>
<body>
<h1>Indexed Collections ใน JavaScript</h1>
<div class="result"></div>
<br />
<button class="Btn">คลิกที่นี่</button>
<h3>คลิกปุ่มด้านบนเพื่อสร้างและแสดง Array</h3>
<script>
const resEle = document.querySelector(".result");
const BtnEle = document.querySelector(".Btn");
BtnEle.addEventListener("click", () => {
const arr = [1, 2, 3, 4, 5];
arr.forEach((item, index) => {
resEle.innerHTML += `arr[${index}] = ${item}<br>`;
});
});
</script>
</body>
</html>
Array Characteristics
- Zero-based Indexing: เริ่มที่ 0
- Dynamic Size: เพิ่ม/ลดได้ตลอดเวลา
- Heterogeneous: เก็บ Type ต่างกันใน Array เดียวได้
- Sparse Arrays: รองรับ Empty Slots (
[1,,3]) - Length Property: อัปเดตอัตโนมัติ
Array Methods สำหรับ Indexed Access
| Category | Methods |
|---|---|
| Access | arr[i], arr.at(index) (ES2022, รองรับ Negative) |
| Add/Remove End | push(), pop() |
| Add/Remove Start | unshift(), shift() |
| Modify Middle | splice(index, deleteCount, ...items) |
| Search | indexOf(), lastIndexOf(), findIndex(), includes() |
| Iterate | forEach(), map(), for...of, entries(), keys(), values() |
Typed Arrays (Binary Data)
// สำหรับ Binary Data, Performance Critical
const int8 = new Int8Array([1, 2, 3]); // 8-bit signed
const uint8 = new Uint8Array([255, 0, 128]); // 8-bit unsigned
const float32 = new Float32Array([1.5, 2.5]); // 32-bit float
const buffer = new ArrayBuffer(16); // Raw Binary Buffer
const view = new DataView(buffer); // Read/Write Mixed Types
Array-like Objects
// Arguments, NodeList, HTMLCollection - มี length และ index แต่ไม่มี Array Methods
const args = (function() { return arguments; })(1, 2, 3);
// Convert to Array:
const arr = Array.from(args); // Modern
const arr2 = [...args]; // Spread (Iterable)
const arr3 = Array.prototype.slice.call(args); // Legacy
ผลลัพธ์
arr[0] = 1, arr[1] = 2, arr[2] = 3, arr[3] = 4, arr[4] = 5