Page 93 - JavaScript
P. 93

In ES 6, the for-of loop is the recommended way of iterating over a the values of an array:


        6


         let myArray = [1, 2, 3, 4];
         for (let value of myArray) {
           let twoValue = value * 2;
           console.log("2 * value is: %d", twoValue);
         }


        The following example shows the difference between a for...of loop and a for...in loop:

        6


         let myArray = [3, 5, 7];
         myArray.foo = "hello";

         for (var i in myArray) {
           console.log(i); // logs 0, 1, 2, "foo"
         }

         for (var i of myArray) {
           console.log(i); // logs 3, 5, 7
         }




        Array.prototype.keys()

        The Array.prototype.keys() method can be used to iterate over indices like this:


        6

         let myArray = [1, 2, 3, 4];
         for (let i of myArray.keys()) {
           let twoValue = myArray[i] * 2;
           console.log("2 * value is: %d", twoValue);
         }




        Array.prototype.forEach()

        The .forEach(...) method is an option in ES 5 and above. It is supported by all modern browsers,
        as well as Internet Explorer 9 and later.


        5

         [1, 2, 3, 4].forEach(function(value, index, arr) {
           var twoValue = value * 2;
           console.log("2 * value is: %d", twoValue);
         });


        Comparing with the traditional for loop, we can't jump out of the loop in .forEach(). In this case,
        use the for loop, or use partial iteration presented below.





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