Array: length
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 |
浏览器兼容性
加载中…