Array.of()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.

Array.of() 静态方法从可变数量的参数创建一个新的 Array 实例,无论参数的数量或类型如何。

¥The Array.of() static method creates a new Array instance from a variable number of arguments, regardless of number or type of the arguments.

Try it

语法

¥Syntax

js
Array.of()
Array.of(element1)
Array.of(element1, element2)
Array.of(element1, element2, /* …, */ elementN)

参数

¥Parameters

element1, …, elementN

用于创建数组的元素。

返回值

¥Return value

一个新的 Array 实例。

¥A new Array instance.

描述

¥Description

Array.of()Array() 构造函数之间的区别在于单个参数的处理:Array.of(7) 创建一个包含单个元素 7 的数组,而 Array(7) 创建一个 length 属性为 7 的空数组。(这意味着 7 个空槽的数组,而不是具有实际 undefined 值的槽。)

¥The difference between Array.of() and the Array() constructor is in the handling of single arguments: Array.of(7) creates an array with a single element, 7, whereas Array(7) creates an empty array with a length property of 7. (That implies an array of 7 empty slots, not slots with actual undefined values.)

js
Array.of(7); // [7]
Array(7); // array of 7 empty slots

Array.of(1, 2, 3); // [1, 2, 3]
Array(1, 2, 3); // [1, 2, 3]

Array.of() 方法是通用工厂方法。例如,如果 Array 的子类继承了 of() 方法,则继承的 of() 方法将返回子类的新实例,而不是 Array 实例。事实上,this 值可以是任何接受表示新数组长度的单个参数的构造函数,并且将使用传递给 of() 的参数数量来调用构造函数。当所有元素都被分配时,最终的 length 将被再次设置。如果 this 值不是构造函数,则使用普通的 Array 构造函数。

¥The Array.of() method is a generic factory method. For example, if a subclass of Array inherits the of() method, the inherited of() method will return new instances of the subclass instead of Array instances. In fact, the this value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to of(). The final length will be set again when all elements are assigned. If the this value is not a constructor function, the plain Array constructor is used instead.

示例

¥Examples

使用 Array.of()

¥Using Array.of()

js
Array.of(1); // [1]
Array.of(1, 2, 3); // [1, 2, 3]
Array.of(undefined); // [undefined]

在非数组构造函数上调用 of()

¥Calling of() on non-array constructors

可以在任何接受表示新数组长度的单个参数的构造函数上调用 of() 方法。

¥The of() method can be called on any constructor function that accepts a single argument representing the length of the new array.

js
function NotArray(len) {
  console.log("NotArray called with length", len);
}

console.log(Array.of.call(NotArray, 1, 2, 3));
// NotArray called with length 3
// NotArray { '0': 1, '1': 2, '2': 3, length: 3 }

console.log(Array.of.call(Object)); // [Number: 0] { length: 0 }

this 值不是构造函数时,返回一个普通的 Array 对象。

¥When the this value is not a constructor, a plain Array object is returned.

js
console.log(Array.of.call({}, 1)); // [ 1 ]

规范

Specification
ECMAScript Language Specification
# sec-array.of

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看