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

前端 未结 5 904
臣服心动
臣服心动 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:20

    It seems pretty valid. I honestly don't think that performance would decrease too much. But there is however one big downside, that is easily fixable: the break statement.

    function repeat(n, f) {
       for (var i = 0; i < n; i++) {
          var tcall=i;
          tcall.die=function(){i=n}
          f.call(tcall);
       }
    }  
    

    This way you would be able to call this.die() instead of break; which I think would throw an error.

提交回复
热议问题