3 ms·
A built-in way to conveniently iterate n times. Anyone have a sensible pure JavaScript example for: range(5).forEach(fn) I haven't found one that
by Waterluvian 8y ago
A built-in way to conveniently iterate n times.
Anyone have a sensible pure JavaScript example for:
range(5).forEach(fn)
I haven't found one that felt small enough to use inline. It end up using traditional for loops.
- blinger 8y agoArray.from({ length: 5 }).forEach(fn)
- Waterluvian 8y agoOh not bad. I wasn't aware of that! I'm guessing it constructs the whole array upfront. Maybe there's a generator way to do it too.
- jimrandomh 8y agoUsing underscorejs or lodash: _.range(5).forEach(i => {/*...*/})
- klardotsh 8y agoI really don't love it, but Array(5).fill().forEach(() => console.log('hello'))
- ljm 8y agoI've also taken to: Array.from({ length: 5 }).forEach(...) But I'm not sure what you gain from that compared to just wrapping a for loop in a function. You still don't get ranges the way you do in, say Ruby: ('a'..'z').each {|letter| puts letter }
- klardotsh 8y agoYeah, I mostly work in Python, where ranging and slicing is amazing. JS has a lot to catch up on in that regard.
- c-smile 8y agoYeah, this for (var n in 5) // n is in [0..5) should just work as it does in Sciter.