Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Array.of()

BaselineWidely available

TheArray.of() static method creates a newArrayinstance from a variable number of arguments, regardless of number or type of thearguments.

Try it

console.log(Array.of("foo", 2, "bar", true));// Expected output: Array ["foo", 2, "bar", true]console.log(Array.of());// Expected output: Array []

Syntax

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

Parameters

element1, …,elementN

Elements used to create the array.

Return value

A newArray instance.

Description

The difference betweenArray.of() and theArray() constructor is in the handling of single arguments:Array.of(7) creates an array with a single element,7, whereasArray(7) creates an empty array with alength property of7. (That implies an array of 7 empty slots, not slots with actualundefined values.)

js
Array.of(7); // [7]Array(7); // array of 7 empty slotsArray.of(1, 2, 3); // [1, 2, 3]Array(1, 2, 3); // [1, 2, 3]

TheArray.of() method is a generic factory method. For example, if a subclass ofArray inherits theof() method, the inheritedof() method will return new instances of the subclass instead ofArray instances. In fact, thethis 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 toof(). The finallength will be set again when all elements are assigned. If thethis value is not a constructor function, the plainArray constructor is used instead.

Examples

Using Array.of()

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

Calling of() on non-array constructors

Theof() 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 }

When thethis value is not a constructor, a plainArray object is returned.

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

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-array.of

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp