Currently, I'm using Array.apply(null, new Array(10)).map(Number.prototype.valueOf, 0);
to create an array of 0.
I'm wondering is there a better (cleaner) way to do this in typescript?
Use the fill() method to create an array filled with zeros, e.g. new Array(3). fill(0) , creates an array containing 3 elements with the value of 0 . The fill() method sets the elements in an array to the provided value and returns the modified array.
To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!
In TypeScript, an array is an ordered list of values. An array can store a mixed type of values. To declare an array of a specific type, you use the let arr: type[] syntax.
for other values use Arrays utility class. int arrayDefaultedToTen[] = new int[100]; Arrays. fill(arrayDefaultedToTen, 10); this method fills the array (first arg) with 10 (second arg).
You can add to the open Array<T>
interface to make the fill
method available. There is a polyfill for Array.prototype.fill on MDN if you want older browser support.
interface Array<T> {
fill(value: T): Array<T>;
}
var arr = Array<number>(10).fill(0);
View on Playground
Eventually the fill
method will find its way into the lib.d.ts
file and you can delete your one (the compiler will warn you when you need to do this).
As of now you can just do
const a = new Array<number>(1000).fill(0);
Make sure you include <number>
otherwise it will infer a
's type as any[]
.
Having reviewed the concept of array holes I would do:
Array.apply(null, new Array(10)).map(()=> 0);
Not a big saving but is some.
You could pass and integer argument to the Array constructor, this will return a new JavaScript array with its length property set to that number, plus you can use .fill
to fills all the elements of an array from index zero.
const data = ([...Array(10).fill(0)])
console.log(data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With