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

วิธีหาความยาวของ Array ใน JavaScript

Property length

Array.length เป็น Property (ไม่ใช่ Method) คืนค่า Unsigned 32-bit Integer ระบุจำนวน Element ใน Array

Syntax

array.length

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

<html>
<head>
  <title>JavaScript Array length Property</title>
</head>
<body>
  <script>
    var arr = new Array(50, 60, 70, 80);
    document.write("arr.length is : " + arr.length);
  </script>
</body>
</html>

ผลลัพธ์

arr.length is : 4

คุณสมบัติพิเศษของ length

1. เขียนได้ (Writable) - สามารถตั้งค่า Length ใหม่

const arr = [1, 2, 3, 4, 5];
arr.length = 2;  // ตัดทอนเหลือ 2 Element แรก
console.log(arr); // [1, 2]

arr.length = 5;  // ขยาย Array (Element ใหม่เป็น empty slots)
console.log(arr); // [1, 2, empty × 3]

2. อัปเดตอัตโนมัติเมื่อเพิ่ม/ลบ Element

const arr = [1, 2];
arr.push(3);      // length = 3
arr[5] = 6;       // length = 6 (Index 3,4 เป็น empty slots)
delete arr[1];    // length ยังคง = 6 (delete ไม่เปลี่ยน length)

Empty Slots vs Undefined

const arr = [1, , 3]; // Empty slot ที่ Index 1
console.log(arr.length); // 3
console.log(arr[1]); // undefined
console.log(1 in arr); // false (Empty Slot)
console.log(Object.keys(arr)); // ['0', '2'] - ข้าม Empty Slot

// vs
const arr2 = [1, undefined, 3];
console.log(1 in arr2); // true

Array-like Objects

Object ที่มี Property length และ Index เป็นตัวเลข ใช้ได้กับ Array Methods ผ่าน call/apply:

const arrayLike = { 0: 'a', 1: 'b', length: 2 };
Array.prototype.forEach.call(arrayLike, (v, i) => console.log(i, v));
// หรือ ES6+
[...arrayLike].forEach(...); // ต้องมี Symbol.iterator
Array.from(arrayLike).forEach(...);

Performance Note

  • เข้าถึง length ใน Loop ให้ Cache ไว้: for (let i = 0, len = arr.length; i < len; i++)
  • แต่ใน JS Engine สมัยใหม่ Optimize ให้แล้ว ไม่ต้อง Cache ก็ได้

สรุป

array.length คือ Property คืนจำนวน Element เขียนได้ (Truncate/Extend Array) อัปเดตอัตโนมัติ รองรับ Array-like Objects เป็น Key Feature ของ JavaScript Arrays