Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Array.fill to create 0...499 in JavaScript?

I want to use Array.fill method to create a sequence from 0...499 like

const arr = []
for(let i = 0; i < 500; i++)
   arr.push(i);

Currently, I am using Array.from like:

const arr = Array.from(Array(500).keys())

But how can I use just Array.fill to create the sequence? Is it even possible?

like image 413
deadcoder0904 Avatar asked Oct 22 '25 15:10

deadcoder0904


1 Answers

No you can't do it with fill alone as fill method adds a static value

The fill() method fills (modifies) all the elements of an array from a start index (default zero) to an end index (default array length) with a static value. It returns the modified array.

console.log(new Array(500).fill(0).map((_,i) => i ))
console.log(Array.from(Array(500).keys()))
like image 100
Code Maniac Avatar answered Oct 25 '25 04:10

Code Maniac