Page 94 - JavaScript
P. 94

In all versions of JavaScript, it is possible to iterate through the indices of an array using a
        traditional C-style for loop.


         var myArray = [1, 2, 3, 4];
         for(var i = 0; i < myArray.length; ++i) {
           var twoValue = myArray[i] * 2;
           console.log("2 * value is: %d", twoValue);
         }


        It's also possible to use while loop:


         var myArray = [1, 2, 3, 4],
             i = 0, sum = 0;
         while(i++ < myArray.length) {
           sum += i;
         }
         console.log(sum);



        Array.prototype.every


        Since ES5, if you want to iterate over a portion of an array, you can use Array.prototype.every,
        which iterates until we return false:

        5


         // [].every() stops once it finds a false result
         // thus, this iteration will stop on value 7 (since 7 % 2 !== 0)
         [2, 4, 7, 9].every(function(value, index, arr) {
           console.log(value);
           return value % 2 === 0; // iterate until an odd number is found
         });


        Equivalent in any JavaScript version:


         var arr = [2, 4, 7, 9];
         for (var i = 0; i < arr.length && (arr[i] % 2 !== 0); i++) { // iterate until an odd number is
         found
           console.log(arr[i]);
         }



        Array.prototype.some

        Array.prototype.some iterates until we return true:


        5


         // [].some stops once it finds a false result
         // thus, this iteration will stop on value 7 (since 7 % 2 !== 0)
         [2, 4, 7, 9].some(function(value, index, arr) {
           console.log(value);
           return value === 7; // iterate until we find value 7
         });



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