What is the best way to do loops in JavaScript

前端 未结 9 1853
温柔的废话
温柔的废话 2020-12-13 00:35

I have stumbled into several methods of looping in JavaScript, what I like the most is:

for(var i = 0; i < a.length; i++){
    var element = a[i];
}


        
相关标签:
9条回答
  • 2020-12-13 01:22

    Just store the length in a variable first.

      var len = a.length;
      for (var i = 0; i < len; i++) {
        var element = a[i];
      }
    
    0 讨论(0)
  • 2020-12-13 01:31

    If you have many elements in the array and speed is an issue then you want to use a while loop that iterates from highest to lowest.

      var i = a.length;
      while( --i >= 0 ) {
        var element = a[i];
        // do stuff with element
      }  
    
    0 讨论(0)
  • 2020-12-13 01:33

    I've started using iterators where relevant. Performance is reasonable, however more importantly it allows you to encapsulate the looping logic:

    function createIterator(x) {
        var i = 0;
    
         return function(){
           return x[i++];
        };
    }
    

    Then to use:

    var iterator=createIterator(['a','b','c','d','e','f','g']);
    
    iterator();
    

    returns "a";

    iterator();
    

    returns "b";

    and so on.

    To iterate the whole list and display each item:

    var current;
    
    while(current=iterator())
    {
        console.log(current);
    }
    

    Be aware that the above is only acceptable for iterating a list that contains "non-falsy" values. If this array contained any of:

    • 0
    • false
    • ""
    • null
    • NaN

    the previous loop would stop at that item, not always what you want/expect.

    To avoid this use:

    var current;
    
    while((current=iterator())!==undefined)
    {
       console.log(current);
    }
    
    0 讨论(0)
提交回复
热议问题