Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 819
kurri sudarshan reddy Avatar asked Dec 02 '22 14:12

kurri sudarshan reddy


2 Answers

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
like image 197
Arun Ghosh Avatar answered Dec 28 '22 23:12

Arun Ghosh


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

  • 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

like image 21
basarat Avatar answered Dec 29 '22 00:12

basarat