Regarding JavaScript for() loop voodoo

前端 未结 9 1435
梦如初夏
梦如初夏 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条回答
  •  -上瘾入骨i
    2021-02-19 09:31

    The generalized format of a for loop (not a for-in loop) is

    for ( EXPRESSION_1 ; EXPRESSION_2 ; EXPRESSION_3 ) STATEMENT
    

    The first EXPRESSION_1 is usually used to initialize the loop variable, EXPRESSION_2 is the looping condition, and EXPRESSION_3 is usually an increment or decrement operation, but there are no rules that say they have to behave like that. It's equivalent to the following while loop:

    EXPRESSION_1;
    while (EXPRESSION_2) {
        STATEMENT
        EXPRESSION_3;
    }
    

    The commas are just an operator that combines two expressions into a single expression, whose value is the second sub-expression. They are used in the for loop because each part (separated by semicolons) needs to be a single expression, not multiple statements. There's really no reason (except maybe to save some space in the file) to write a for loop like that since this is equivalent:

    shuffle = function(o) {
        var j, x;
        for (var i = o.length; i > 0; i--) {
            j = parseInt(Math.random() * i);
            x = o[i - 1];
            o[i - 1] = o[j];
            o[j] = x;
        }
        return o;
    };
    

提交回复
热议问题