Do loops check the array.length every time when comparing i against array.length?

前端 未结 5 1556
一向
一向 2020-11-30 07:44

I was browsing around and I found this:

var i, len;
for(i = 0, len = array.length; i < len; i++) {  
   //...
}

My first thoughts are:

5条回答
  •  醉酒成梦
    2020-11-30 07:53

    One reason to do this is say, if you're adding elements to the array during the loop but do not want to iterate over them. Say you want to turn [1, 2, 3] into [1, 2, 3, 1, 2, 3]. You could to that with:

    var initialLength = items.length;
    for(var i=0; i

    If you don't save the length before the loop, then array.length will keep increasing and the loop will run until the browser crashes / kills it.

    Other than that, as the others said, it mildly affects performance. I wouldn't make a habit out of doing this because "premature optimization is the root of all evil". Plus, if you change the size of the array during the loop, doing this could break your code. For instance, if you remove elements from the array during the loop but keep comparing i to the previous array size, then the loop will try to access elements beyond the new size.

提交回复
热议问题