do <something> N times (declarative syntax)
Is there a way in Javascript to write something like this easily:
[1,2,3].times do {
something();
}
Any library that might support some similar syntax maybe?
Update: to clarify - I would like something()
to be called 1,2 and 3 times respectively for each array element iteration
Solution 1:
Just use a for
loop:
var times = 10;
for(var i = 0; i < times; i++){
doSomething();
}
Solution 2:
Possible ES6 alternative.
Array.from(Array(3)).forEach((x, i) => {
something();
});
And, if you want it "to be called 1,2 and 3 times respectively".
Array.from(Array(3)).forEach((x, i) => {
Array.from(Array(i+1)).forEach((x, i2) => {
console.log(`Something ${ i } ${ i2 }`)
});
});
Update:
Taken from filling-arrays-with-undefined
This seems to be a more optimised way of creating the initial array, I've also updated this to use the second parameter map function suggested by @felix-eve.
Array.from({ length: 3 }, (x, i) => {
something();
});
Solution 3:
This answer is based on Array.forEach
, without any library, just native vanilla.
To basically call something()
3 times, use:
[1,2,3].forEach(function(i) {
something();
});
considering the following function:
function something(){ console.log('something') }
The output will be:
something
something
something
To complete this questions, here's a way to do call something()
1, 2 and 3 times respectively:
It's 2017, you may use ES6:
[1,2,3].forEach(i => Array(i).fill(i).forEach(_ => {
something()
}))
or in good old ES5:
[1,2,3].forEach(function(i) {
Array(i).fill(i).forEach(function() {
something()
})
}))
In both cases, the output will be
The output will be:
something
something
something
something
something
something
(once, then twice, then 3 times)