在JavaScript中循环x次的典型方法是:
for (var i = 0; i < x; i++)
doStuff(i);
但我不想使用++运算符或任何可变变量。那么在ES6中,是否有一种方法来循环x乘以另一种方法?我喜欢Ruby的机制:
x.times do |i|
do_stuff(i)
end
JavaScript/ES6中有类似的吗?我可以欺骗自己的生成器:
function* times(x) {
for (var i = 0; i < x; i++)
yield i;
}
for (var i of times(5)) {
console.log(i);
}
当然,我仍然在使用i++。至少它在视线之外:),但我希望在ES6中有更好的机制。
此解决方案的优点
最容易阅读/使用(我觉得)
返回值可以用作和,也可以忽略
普通es6版本,也链接到TypeScript版本的代码
缺点
——突变。只是内在我不在乎,也许其他人也不在乎。
示例和代码
times(5, 3) // 15 (3+3+3+3+3)
times(5, (i) => Math.pow(2,i) ) // 31 (1+2+4+8+16)
times(5, '<br/>') // <br/><br/><br/><br/><br/>
times(3, (i, count) => { // name[0], name[1], name[2]
let n = 'name[' + i + ']'
if (i < count-1)
n += ', '
return n
})
function times(count, callbackOrScalar) {
let type = typeof callbackOrScalar
let sum
if (type === 'number') sum = 0
else if (type === 'string') sum = ''
for (let j = 0; j < count; j++) {
if (type === 'function') {
const callback = callbackOrScalar
const result = callback(j, count)
if (typeof result === 'number' || typeof result === 'string')
sum = sum === undefined ? result : sum + result
}
else if (type === 'number' || type === 'string') {
const scalar = callbackOrScalar
sum = sum === undefined ? scalar : sum + scalar
}
}
return sum
}
TypeScipt版本
https://codepen.io/whitneyland/pen/aVjaaE?editors=0011
我做了这个:
function repeat(func, times) {
for (var i=0; i<times; i++) {
func(i);
}
}
用法:
repeat(function(i) {
console.log("Hello, World! - "+i);
}, 5)
/*
Returns:
Hello, World! - 0
Hello, World! - 1
Hello, World! - 2
Hello, World! - 3
Hello, World! - 4
*/
变量i返回它循环的次数-如果你需要预加载x数量的图像,这很有用。