Javascript for loop efficiency

后端 未结 5 602
我寻月下人不归
我寻月下人不归 2021-01-04 10:01

Is

for (var i=0, cols=columns.length; i

more efficient than

for (var i=0; i

        
5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-04 10:34

    Note that most of these loops require an additional statement in the loop to actually retrieve the i'th element from the array. You can avoid that and get a very fast loop with the following variant, which takes advantage of the fact that Javascript just returns undefined (which evaluates to false), if you access an array with an out of bounds index (rather than raising an error):

    for (var i = 0, col; col = columns[i]; ++i) { ... }

    Obviously this doesn't work if you're iterating through an array which contains elements which would evaluate to false.

提交回复
热议问题