在Javascript中有没有一种方法可以很容易地编写这样的东西:
[1,2,3].times do {
something();
}
有可能支持类似语法的库吗?
Update: to clarify - I would like something()
to be called 1,2 and 3 times respectively for each array element iteration
在Javascript中有没有一种方法可以很容易地编写这样的东西:
[1,2,3].times do {
something();
}
有可能支持类似语法的库吗?
Update: to clarify - I would like something()
to be called 1,2 and 3 times respectively for each array element iteration
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();
});
考虑到以下功能:
function something(){ console.log('something') }
输出将是:
something
something
something
To complete this questions, here's a way to do call something()
1, 2 and 3 times respectively:
[1,2,3].forEach(i => Array(i).fill(i).forEach(_ => {
something()
}))
[1,2,3].forEach(function(i) {
Array(i).fill(i).forEach(function() {
something()
})
}))
在这两种情况下,输出都是
输出将是:
something
something
something
something
something
something
(一次,然后两次,然后三次)