0

these are few examples of the Array constructor use.

var arr2 = new Array(50); // returns [50 empty elements]
var arr3 = new Array(1, 2, "three", 4, "five"); // returns [1, 2, 'three', 4, "five"]
var arr4 = new Array([1, 2, 3, 4, 5]); // returns [[1, 2, 3, 4, 5]] ```

if i want to construct an array with only one element say 4. [4] How do i construct using the array constructor? If i use new Array(4) it will construct an array of length 4 with four empty elements [4 empty elements].

6
  • please post a test input and the desired output Commented Sep 5, 2021 at 10:57
  • Why not just write var arr = [4]? Commented Sep 5, 2021 at 10:58
  • i want to understand whether it's possible to construct an array with the array Constructor which has only one number element. Commented Sep 5, 2021 at 10:59
  • 2
    @aryansingh This is the reason why Array.of(4) was created. Commented Sep 5, 2021 at 11:02
  • 1
    As far as I know, not possible. But I have never used the Array constructor (except as new Array(n) to construct a n-length array), and I don't think I have ever seen it used, so this is not a big loss. Use a literal when you need to specify a hard-coded array, use various Array (and other) methods to make arrays dynamically... and don't use var now that we have const and let. Commented Sep 5, 2021 at 11:03

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.