Array() 构造函数

Array() 构造函数创建 Array 对象。

¥The Array() constructor creates Array objects.

语法

¥Syntax

js
new Array()
new Array(element1)
new Array(element1, element2)
new Array(element1, element2, /* …, */ elementN)
new Array(arrayLength)

Array()
Array(element1)
Array(element1, element2)
Array(element1, element2, /* …, */ elementN)
Array(arrayLength)

注意:可以使用或不使用 new 来调用 Array()。两者都会创建一个新的 Array 实例。

¥Note: Array() can be called with or without new. Both create a new Array instance.

参数

¥Parameters

element1, …, elementN

JavaScript 数组使用给定元素进行初始化,除非将单个参数传递给 Array 构造函数并且该参数是数字(请参阅下面的 arrayLength 参数)。请注意,这种特殊情况仅适用于使用 Array 构造函数创建的 JavaScript 数组,而不适用于使用方括号语法创建的数组文字。

arrayLength

如果传递给 Array 构造函数的唯一参数是 0 到 2 之间的整数32 - 1(含),这将返回一个新的 JavaScript 数组,其 length 属性设置为该数字(注意:这意味着 arrayLength 空槽的数组,而不是具有实际 undefined 值的槽 - 请参阅 稀疏数组)。

例外情况

¥Exceptions

RangeError

如果只有一个参数 (arrayLength) 是数字,但其值不是整数或不在 0 到 232 之间,则抛出该错误 - 1(含)。

示例

¥Examples

数组字面量表示法

¥Array literal notation

可以使用 literal 表示法创建数组:

¥Arrays can be created using the literal notation:

js
const fruits = ["Apple", "Banana"];

console.log(fruits.length); // 2
console.log(fruits[0]); // "Apple"

具有单个参数的数组构造函数

¥Array constructor with a single parameter

可以使用带有单个数字参数的构造函数创建数组。创建一个数组,其 length 属性设置为该数字,并且数组元素是空槽。

¥Arrays can be created using a constructor with a single number parameter. An array is created with its length property set to that number, and the array elements are empty slots.

js
const arrayEmpty = new Array(2);

console.log(arrayEmpty.length); // 2
console.log(arrayEmpty[0]); // undefined; actually, it is an empty slot
console.log(0 in arrayEmpty); // false
console.log(1 in arrayEmpty); // false
js
const arrayOfOne = new Array("2"); // Not the number 2 but the string "2"

console.log(arrayOfOne.length); // 1
console.log(arrayOfOne[0]); // "2"

具有多个参数的数组构造函数

¥Array constructor with multiple parameters

如果将多个参数传递给构造函数,则会创建一个具有给定元素的新 Array

¥If more than one argument is passed to the constructor, a new Array with the given elements is created.

js
const fruits = new Array("Apple", "Banana");

console.log(fruits.length); // 2
console.log(fruits[0]); // "Apple"

规范

Specification
ECMAScript Language Specification
# sec-array-constructor

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also