[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/length [Back]  [Original]

Arraylength - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Arraylength

20157

length Array 32

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

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

232

Arraylength

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); // 
// 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; //  5 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;
}
//  [2, 4, 6, 8, 10]

3 numbers 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

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 2027 LanguageSpecification
# sec-properties-of-array-instances-length


Web Proxy Viewer  |  New URL  |  Original Page