Regarding JavaScript for() loop voodoo

前端 未结 9 1469
梦如初夏
梦如初夏 2021-02-19 08:53

I was for quite some time under the impression that a for loop could exist solely in the following format:

for (INITIALIZER; STOP CONDITION         


        
9条回答
  •  终归单人心
    2021-02-19 09:46

    shuffle = function(o){
         for (
              var j,                // declare j
                  x,                // declare x
                  i = o.length;     // declare i and set to o.length
              i;                    // loop while i evaluates true
              j = parseInt(Math.random() * i), // j=random number up to i
                x = o[--i],         // decrement i, and look up this index of o
                o[i] =  o[j],       // copy the jth value into the ith position
                o[j] = x            // complete the swap by putting the old o[i] into jth position
              );
         return o;
         };
    

    This is starting with i equal to the number of positions, and each time swapping the cards i and j, where j is some random number up to i each time, as per the algorithm.

    It could be more simply written without the confusing comma-set, true.

    By the way, this is not the only kind of for loop in javascript. There is also:

     for(var key in arr) {
          value = arr[key]);
     }
    

    But be careful because this will also loop through the properties of an object, including if you pass in an Array object.

提交回复
热议问题