Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript create empty array of a given size

Tags:

javascript

in javascript how would I create an empty array of a given size

Psuedo code:

X = 3;
createarray(myarray, X, "");

output:

   myarray = ["","",""]
like image 209
gus Avatar asked Sep 29 '22 02:09

gus


People also ask

How do you make an array a certain size?

One common way of creating an Array with a given length, is to use the Array constructor: const LEN = 3; const arr = new Array(LEN); assert. equal(arr. length, LEN); // arr only has holes in it assert.

Can you create an empty array in JS?

The first way is that you can get an empty array by assigning the array literal notation to a variable as follows: let firstArr = []; let secondArr = ["Nathan", "Jack"]; The square brackets symbol [] is a symbol that starts and ends an array data type, so you can use it to assign an empty array.

How do you create an empty array of length n?

To create an empty array of a specific length, let's say 5 , we will pass null as the first argument, and the second is the array Array(5) . This will create an array of length 5 and initialize each element with an undefined value. Alternatively, you can also do the following.

How do you create an empty array?

1) Assigning it to a new empty array This is the fastest way to empty an array: a = []; This code assigned the array a to a new empty array. It works perfectly if you do not have any references to the original array.


2 Answers

1) To create new array which, you cannot iterate over, you can use array constructor:

Array(100) or new Array(100)


2) You can create new array, which can be iterated over like below:

a) All JavaScript versions

  • Array.apply: Array.apply(null, Array(100))

b) From ES6 JavaScript version

  • Destructuring operator: [...Array(100)]
  • Array.prototype.fill Array(100).fill(undefined)
  • Array.from Array.from({ length: 100 })

You can map over these arrays like below.

  • Array(4).fill(null).map((u, i) => i) [0, 1, 2, 3]

  • [...Array(4)].map((u, i) => i) [0, 1, 2, 3]

  • Array.apply(null, Array(4)).map((u, i) => i) [0, 1, 2, 3]

  • Array.from({ length: 4 }).map((u, i) => i) [0, 1, 2, 3]

like image 335
stpoa Avatar answered Oct 21 '22 06:10

stpoa


var arr = new Array(5);
console.log(arr.length) // 5
like image 95
mariocatch Avatar answered Oct 21 '22 06:10

mariocatch