简体   繁体   English

如何将数组的所有成员初始化为typescript中的相同值?

[英]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`

More 更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在打字稿中投射所有成员? - How to cast with all members in typescript? 如何在TypeScript中初始化(声明)数组? - How to initialize (declare) an array in TypeScript? 如何在 Typescript 中初始化一个空的对象数组? - How to initialize an empty array of objects in Typescript? 如何在TypeScript中将数组初始化为元组类型? - How to initialize array to tuple type in TypeScript? 如何在 TypeScript 中实例化、初始化和填充数组? - How to instantiate, initialize and populate an array in TypeScript? 如何强制一个联合的所有成员都将出现在一个对象数组中? 如何将数组简化为 object 并以所有联合成员作为键? - How to enforce all members of a union will be present in an array of objects? How to reduce the array to an object with all union members as keys? 匹配所有数组成员不包含值的文档 - Match Documents where all array members do not contain a value Typescript 如何使用类转换器初始化混合类型数组 - Typescript How to initialize mixed type array with class-transformer 打字稿初始化二维数组 - Typescript initialize two dimensional array 如何获取数组中相同值的所有出现的索引? - How to get index of all occurences of the same value in an Array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM