Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Greg Fletcher
Greg Fletcher

Posted on

     

Instant Arrays, Javascript

Here's a cool way to quickly make arrays in Javascript.

letarray=Array(10).fill()

This creates an array with ten slots in it. I usually find this useful if I need to quickly iterate over a list in React. For me, this is a nice quick way to check if my styling is working. For example, what if we wanted to know what a component would look like with 10 list items compared to 20.

Example below

constList=()=><div>{Array(10).fill().map((_,i)=><pkey={i}>Text</p>)}</div>;

What's great about this is that I just change one number and get an entirely different numbered array. No need to manually type out the array yourself.

Sometimes though it's also useful to have an ordered array. This is also quite easy to achieve.

letarray=Array(5).fill().map((_,index)=>index+1);// 1,2,3,4,5

Here we're just using theindex of the array and returning it after adding1. This gives us an array with five elements ranging from 1 to 5

If we didn't need an ordered array we could just provide.fill anargument and fill the entire array with that value.

letarray=Array(100).fill(2);// [2,2,2,2,2...etc]

So there we have it, I hope that you learned something from this article. I love learning new coding tricks so definitely let me know if you have anything cool to share in the comments!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

loop {refactoring()}
  • Work
    Full Stack at Freelance
  • Joined

More fromGreg Fletcher

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp