Page 92 - JavaScript
P. 92

var i = 0, length = myArray.length;
         for (; i < length;) {
             console.log(myArray[i]);
             i++;
         }


        ... or this one:


         var key = 0, value;
         for (; value = myArray[key++];){
             console.log(value);
         }


        Whichever works best is largely a matter of both personal taste and the specific use case you're
        implementing.

        Note that each of these variations is supported by all browsers, including very very old ones!




        A while loop


        One alternative to a for loop is a while loop. To loop through an array, you could do this:


         var key = 0;
         while(value = myArray[key++]){
             console.log(value);
         }

        Like traditional for loops, while loops are supported by even the oldest of browsers.


        Also, note that every while loop can be rewritten as a for loop. For example, the while loop
        hereabove behaves the exact same way as this for-loop:


         for(var key = 0; value = myArray[key++];){
             console.log(value);
         }



        for...in


        In JavaScript, you can also do this:


         for (i in myArray) {
             console.log(myArray[i]);
         }


        This should be used with care, however, as it doesn't behave the same as a traditional for loop in
        all cases, and there are potential side-effects that need to be considered. See Why is using
        "for...in" with array iteration a bad idea? for more details.


        for...of



        https://riptutorial.com/                                                                               49
   87   88   89   90   91   92   93   94   95   96   97