[JavaScript] Creating an array of desired length on the fly

Hwanhoon KIM·2024년 5월 1일

Creating an array of desired length on the fly

If you need to generate an array of a specific length, whether for testing purposes or any other scenario, you can achieve it quite elegantly like this:

// For instance, let's create an array with a length of 10.
// You can insert any value inside the fill method.
const arr = Array(10).fill(0).map((_, i) => i)
// arr = [0, 1, 2, ..., 8, 9]

Isn't it straightforward right?
fill 0 in an array whose length is 10. And map it however you want. Voilà !

profile
Fullstack Developer, I post about HTML, CSS(SASS, LESS), JavaScript, React, Next, TypeScript.

0개의 댓글