kurri sudarshan reddy
kurri sudarshan reddy

Reputation: 113

How to initialize all members of an array to the same value in typescript?

In C Language int myArray[42] = { 0 }; initialises all the values of the array to 0 at the start. Is there any similar way that we can do in typescript?

Upvotes: 6

Views: 11113

Answers (2)

basarat
basarat

Reputation: 275947

In C Language int myArray[42] = { 0 }; initialises all the values of the array to 0 at the start. Is there any similar way that we can do in typescript

In JavaScript latest you can use Array.from :

Array.from({length:10}); // Array of `undefined x 10`

Of course you can make it something else too:

Array.from({length:10}).map(x=>0); // Array of `0 x 10`

More

Upvotes: 6

Arun Ghosh
Arun Ghosh

Reputation: 7744

You can use Array.prototype.fill()

The fill() method fills all the elements of an array from a start index to an end index with a static value.

var arr = new Array(30);
arr.fill(0); // Fills all elements of array with 0

Upvotes: 14

Related Questions