JavaScript of()Method

Array 对象参考手册JavaScript Array Object

Example

Convert a set of values into an array:

var myArr = Array.of("Example","Google","Taobao");

Try it Yourself »

Definition and Usage

The of() method is used to convert a set of values into an array, regardless of the number or type of parameters.

The difference between Array.of() and the Array() constructor lies in the handling of a single parameter: Array.of(7) creates an array with a single element 7, while Array(7) creates an empty array with a length of 7.

Returns true if the object is an array, otherwise returns false.


Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method
of() 45.0 12.0 32.0 9 25.0

Syntax

Array.of(element0)
Array.of(element0, element1)
Array.of(element0, element1, /* … ,*/ elementN)

Parameters

Parameter Description
element0 Required. The element to be converted into an array.
element1, /* … ,*/ elementN Optional. The element to be converted into an array.
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]

Technical Details

Return value: An array object.
JavaScript Version: ECMAScript 6

More Examples

Using Array.of():

Example

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

Calling of() with a non-array constructor:

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

Example

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 the this value is not a constructor, a plain Array object is returned.

Example

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


Array 对象参考手册JavaScript Array Object

Other Extensions