Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript of() method

JavaScript of() method

Array Object Reference JavaScript Array object

Example

Convert a set of values to an array:

var

myArr

=

Array

.

of

(

"

Runoob

"

,

"

Google

"

,

"

Taobao

"

)

;

Try it »


Definition and Usage

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

The difference between the Array.of() and Array() constructors lies in how a single argument is handled: 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 indicate the first browser version that supports this 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

Parameters Description
element0 Required. The element to be converted to an array.
element1, / ... ,/ elementN Optional. The element to be converted to 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() on a non-array constructor:

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

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 Object Reference JavaScript Array object