The typical way to loop x
times in JavaScript is:
for (var i = 0; i < x; i++)
doStuff(i);
But I don’t want to use the ++
operator or have any mutable variables at all. So is there a way, in ES6, to loop x
times another way? I love Ruby’s mechanism:
x.times do |i|
do_stuff(i)
end
Anything similar in JavaScript/ES6? I could kind of cheat and make my own generator:
function* times(x) {
for (var i = 0; i < x; i++)
yield i;
}
for (var i of times(5)) {
console.log(i);
}
Of course I’m still using i++
. At least it’s out of sight :), but I’m hoping there’s a better mechanism in ES6.