length
為Array物件的屬性
,可供設定或回傳該陣列實體中包含的元素個數。其值必為一大於零、32位元、且恆大於該陣列最大索引數的正整數。
var items = ['shoes', 'shirts', 'socks', 'sweaters'];
items.length;
// returns 4
描述
length
屬性的值必為一正整數,其值必介於 0 ~ 232 (不包含)之間.
var namelistA = new Array(4294967296); //232 = 4294967296
var namelistC = new Array(-100) //負數
console.log(namelistA.length); //RangeError: Invalid array length
console.log(namelistC.length); //RangeError: Invalid array length
var namelistB = [];
namelistB.length = Math.pow(2,32)-1; //將長度設定介於 0 ~ 232 -1
console.log(namelistB.length);
//4294967295
你可以透過改變 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 與數值屬性的關係。
Property attributes of Array.length |
|
---|---|
Writable | yes |
Enumerable | no |
Configurable | no |
範例
對陣列進行迭代處理
以下範例中, 陣列 numbers
透過 length
屬性進行迭代操作,並將其內容值加倍。
var numbers = [1, 2, 3, 4, 5];
var length = numbers.length;
for (var i = 0; i < length; i++) {
numbers[i] *= 2;
}
// numbers 內容值變為 [2, 4, 6, 8, 10]
縮減陣列
以下範例中, 陣列 numbers
的長度若大於 3,則將其長度縮減至 3。
var numbers = [1, 2, 3, 4, 5];
if (numbers.length > 3) {
numbers.length = 3;
}
console.log(numbers); // [1, 2, 3]
console.log(numbers.length); // 3
規格
Specification | Status | Comment |
---|---|---|
ECMAScript 1st Edition (ECMA-262) | Standard | Initial definition. |
ECMAScript 5.1 (ECMA-262) The definition of 'Array.length' in that specification. |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Array.length' in that specification. |
Standard | |
ECMAScript (ECMA-262) The definition of 'Array.length' in that specification. |
Living Standard |
瀏覽器相容性
BCD tables only load in the browser
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.