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
语法
参数
返回值
描述
¥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.)
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.
示例
使用 Array.of()
在非数组构造函数上调用 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.
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.
console.log(Array.of.call({}, 1)); // [ 1 ]
规范
Specification |
---|
ECMAScript Language Specification # sec-array.of |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also