Array: length

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Array 例項的 length 資料屬性表示該陣列中的元素數量。其值是一個無符號 32 位整數,其數值始終大於陣列中的最高索引。

試一試

const clothing = ["shoes", "shirts", "socks", "sweaters"];

console.log(clothing.length);
// Expected output: 4

小於 232 的非負整數。

Array: length 的屬性特性
可寫
可列舉
可配置

描述

length 屬性的值是一個小於 232 的非負整數。

js
const listA = [1, 2, 3];
const listB = new Array(6);

console.log(listA.length);
// 3

console.log(listB.length);
// 6

listB.length = 2 ** 32; // 4294967296
// RangeError: Invalid array length

const listC = new Array(-100); // Negative numbers are not allowed
// RangeError: Invalid array length

陣列物件會觀察 length 屬性,並自動將 length 值與其陣列內容同步。這意味著:

  • length 設定為小於當前長度的值會截斷陣列——超出新 length 的元素將被刪除。
  • 將當前 length 之外的任意陣列索引(小於 232 的非負整數)設定為值會擴充套件陣列——length 屬性會增加以反映新的最高索引。
  • length 設定為無效值(例如,負數或非整數)會丟擲 RangeError 異常。

length 被設定為大於當前長度的值時,陣列會透過新增空位來擴充套件,而不是實際的 undefined 值。空位與陣列方法有一些特殊的互動;請參閱陣列方法和空位

js
const arr = [1, 2];
console.log(arr);
// [ 1, 2 ]

arr.length = 5; // set array length to 5 while currently 2.
console.log(arr);
// [ 1, 2, <3 empty items> ]

arr.forEach((element) => console.log(element));
// 1
// 2

另請參閱length 和數值屬性之間的關係

示例

迭代陣列

在下面的示例中,透過檢視 length 屬性來迭代 numbers 陣列。然後將每個元素的值加倍。

js
const numbers = [1, 2, 3, 4, 5];
const length = numbers.length;
for (let i = 0; i < length; i++) {
  numbers[i] *= 2;
}
// numbers is now [2, 4, 6, 8, 10]

縮短陣列

下面的示例將 numbers 陣列縮短為長度 3,前提是當前長度大於 3。

js
const numbers = [1, 2, 3, 4, 5];

if (numbers.length > 3) {
  numbers.length = 3;
}

console.log(numbers); // [1, 2, 3]
console.log(numbers.length); // 3
console.log(numbers[3]); // undefined; the extra elements are deleted

建立固定長度的空陣列

length 設定為大於當前長度的值會建立一個稀疏陣列

js
const numbers = [];
numbers.length = 3;
console.log(numbers); // [empty x 3]

長度不可寫的陣列

當元素新增到當前長度之外時,陣列會自動更新 length 屬性。如果 length 屬性被設定為不可寫,陣列將無法更新它。這會在嚴格模式下導致錯誤。

js
"use strict";

const numbers = [1, 2, 3, 4, 5];
Object.defineProperty(numbers, "length", { writable: false });
numbers[5] = 6; // TypeError: Cannot assign to read only property 'length' of object '[object Array]'
numbers.push(5); // // TypeError: Cannot assign to read only property 'length' of object '[object Array]'

規範

規範
ECMAScript® 2026 語言規範
# sec-properties-of-array-instances-length

瀏覽器相容性

另見