Creating continuous array of natural numbers by using Array.from
Comment | 0ViewIt’s a month that I don’t write anything because my busyness almost drive me crazy. Today there is a small demand to creat a continuous array of natural numbers that it’s items are all less than current hour. I think it a good idea to write it down.
It’s easy to generate a array starts from 0 and contains n consecutive natural numbers by using for
:
1 | let arr = []; |
But the code is too long for me. After checking the documentation, I noticed the interface Array.from
can do the same thing and SHORTER.
1 | Array.from({ length: n }, (item, idx) => idx); |
Fixed in ONE line.
The idea is using Array
to generate the very length array, then we take item’s index as final result.
Fist of all, we use Array.form({ length: n })
to create a array which length is n, items are all undefined
. Then we pass a function to the interface’s second parameter which is a map function, now we can get the item’s index.
After getting the array, the last part is simple:
1 | let now = new Date(); |
EOF.
- Blog Link: https://blog.decay.fun/en/2019/09/24/learning-javascript-api-array-from/
- Copyright Declaration: The author owns the copyright. Please indicate the source reproduced!
Share用中文浏览本文