How can I create an array of zeros in typescript?

I am currently using Array.apply(null, new Array(10)).map(Number.prototype.valueOf, 0);

to create an array from 0.

I'm wondering if there is a better (cleaner) way to do this in typescript?

+3


source to share


3 answers


You can add to a public interface Array<T>

to make the method fill

available. There is a polyfill for Array.prototype.fill on MDN if you need older browser support.

interface Array<T> {
    fill(value: T): Array<T>;
}

var arr = Array<number>(10).fill(0);

      



Playground viewing

Eventually the method fill

will find its way into the file lib.d.ts

and you can delete it (the compiler will warn you when you need it).

+4


source


After considering the concept of holes in an array, I would do:

Array.apply(null, new Array(10)).map(()=> 0);

      



Not a big savings, but some.

+3


source


You can also pass an integer argument to the Array constructor, this will return a new JavaScript array with its length property set to that number. Alternatively, you can use .fill

zero-based index to populate all array elements.

const data = ([...Array(10).fill(0)])
console.log(data)
      

Run codeHide result


0


source







All Articles