Regarding JavaScript for() loop voodoo

前端 未结 9 1488
梦如初夏
梦如初夏 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:40

    They've pretty much just moved the body of the loop into the incrementer section. You can re-write the for loop as a while loop to get some idea of what it is doing:

     shuffle=function(o) {
        var j; //Random position from 0 up to the current position - 1
        var x; //temp holder for swapping positions
        var i=o.length; //current position
        while(i>0) { // Loop through the array
            j = parseInt(Math.random()*i); //get a lower position
            x = o[--i]; // decrement the position and store that position's value in the temp var
            o[i]=o[j]; // copy position j to position i
            o[j]=x; // copy the temp value that stored the old value at position i into position j
        }
        return o;
    }
    

    The first three var's are the initialzier expanded out, the check in the while is the stop condition and the body of the while is what was done in the incrementer portion of the for.

    Edit: Corrected per Gumbo's comment

提交回复
热议问题