[英]How to initialize all members of an array to the same value in typescript?
In C Language int myArray[42] = { 0 }; 在C语言中,myArray [42] = {0}; initialises all the values of the array to 0 at the start. 在开始时将数组的所有值初始化为0。 Is there any similar way that we can do in typescript? 我们可以用打字稿做类似的方式吗?
You can use Array.prototype.fill() 你可以使用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. fill()方法使用静态值将数组的所有元素从起始索引填充到结束索引。
var arr = new Array(30);
arr.fill(0); // Fills all elements of array with 0
In C Language int myArray[42] = { 0 }; 在C语言中,myArray [42] = {0}; initialises all the values of the array to 0 at the start. 在开始时将数组的所有值初始化为0。 Is there any similar way that we can do in typescript 我们可以用打字稿做类似的方式
In JavaScript latest you can use Array.from
: 在JavaScript最新版中,您可以使用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 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 使用lib
选项: https : //basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html#lib-option
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.