Get to know MDN better
此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
length 為 Array 物件的屬性,可供設定或回傳該陣列實體中包含的元素個數。其值必為一大於零、32 位元、且恆大於該陣列最大索引數的正整數。
length 屬性的值必為一正整數,其值必介於 0 ~ 2^32 (不包含)之間.
你可以透過改變 length 屬性來改變陣列的長度。當你透過 length 屬性來增加陣列的長度時,陣列中實際的元素也會隨之增加。舉例來說,當你將 array.length 由 2 增加為 3,則改動後該陣列即擁有 3 個元素,該新增的元素則會是一個不可迭代(non-iterable)的空槽(empty slot)。
const arr = [1, 2]; console.log(arr); // [ 1, 2 ] arr.length = 5; // 將arr的length由2改成5 console.log(arr); // [ 1, 2, <3 empty items> ] arr.forEach(element => console.log(element)); // 空元素無法被迭代 // 1 // 2如上所見,length 屬性不盡然代表陣列中所有已定義的元素個數。詳見 length 與數值屬性的關係。
| 可寫 | 是 |
| 可列舉 | 否 |
| 可配置 | 否 |
以下範例中, 陣列 numbers 透過 length 屬性進行迭代操作,並將其內容值加倍。
以下範例中, 陣列 numbers 的長度若大於 3,則將其長度縮減至 3。
| ECMAScript® 2027 Language Specification # sec-properties-of-array-instances-length |
Enable JavaScript to view this browser compatibility table.
This page was last modified on 2025年7月14日 by MDN contributors.
Your blueprint for a better internet.
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under a Creative Commons license.