Reputation: 113
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
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`
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from
use lib
option : https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html#lib-option
Upvotes: 6
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