JavaScript for-loop alternative: repeat(n, function(i) { … });

前端 未结 5 890
臣服心动
臣服心动 2021-02-09 22:05

This is the regular for-loop:

for (var i = 0; i < n; i++) { ... }

It is used to iterate over arrays, but also to just repeat some process

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-09 22:38

    You say you want a revolution... Well, you know: ruby did it just before (?)

    Number.prototype.times = function(func) { 
        for(var i = 0; i < Number(this); i++) {
            func(i); 
        }
    }
    

    means

    (50).times(function(i) {
        console.log(i)
    })
    

    Anyway, don't fight against C, you'll always lose :-P

提交回复
热议问题