Regarding JavaScript for() loop voodoo

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

    The code you quote is obfuscated in my opinion. There are much clearer ways to write the same functionality.

    However, your understanding is pretty much right. The following is the exact same code, except for whitespace and comments.

    for (
         // Initializer
         var j, x, i = o.length;
         // Continue condition
         i;
         // Operation to be carried out on each loop
         j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x
     )
     // empty body, equivalent to { }
     ;
    

    It's much clearer to write the equivalent:

    var j,x,i = o.length;
    while(i) {
        j = parseInt(Math.random() * i);
        x = o[--i];
        o[i] = o[j];
        o[j] = x;
    }
    

    There are other optimisations that could be made for readability - including using while(i > 0) instead of while(i), and splitting out the --i into an i-- on a separate line.

    There's really no reason for for() to exist, except for readability. These two are equivalent:

    { // this block is to scope int i
       int i=0;
       while(i<100) {
           myfunc(i);
           i++;
       }
    }
    
    for(int i=0; i<100; i++) {
        myfunc(i);
    }
    

    You should use whichever is most readable for a given time. I'd argue that the author of your code has done the opposite. In fairness, he may have done this in order to achieve a smaller JS file for faster loading (this is the kind of transform an automated code compactor could do).

提交回复
热议问题