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)
For further actions, you may consider blocking this person and/orreporting abuse