简体   繁体   中英

How to create an array of zeros in typescript?

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?

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).

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.

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[] .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM