[Javascript] Array.of

We have new Arrayin Javascript

const arr1 = new Array(3) // create an empty array with lengh 3
const arr2 = new Array(1,2,3) // create an array with values: [1,2,3]

Depends on the params you pass to the Array constructor, it behiavor differently.

If you just pass 1 param, the param represent the length of the Array

If you pass multi params, then the params represent the items of the Array

The difference might cause some confusion.

 

Since ES6, introduces Array.of, which resolve the issue of new Array

const arr1 = Array.of(3) // Create an array with value: [3]
const arr2 = Array.of(1,2,3) // Create an array with values: [1,2,3]

 

posted @ 2025-06-02 14:06  Zhentiw  阅读(8)  评论(0)    收藏  举报