A for loop without any {}

后端 未结 6 1882
借酒劲吻你
借酒劲吻你 2020-12-10 18:10

So I was reading about shuffling an array. And then I came across this script:

shuffle = function(o){ //v1.0
    for(var j, x, i = o.length; i; j = parseInt(         


        
6条回答
  •  [愿得一人]
    2020-12-10 18:46

    All the work is actually being done within the parens of the for statement. There is not explicit body for the loop so the ; at the end just says that the body is an empty statement.

    The , (comma) operator evaluates expressions from left to right, and returns the value of the right-most.

    The loop is basically equivalent to:

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

提交回复
热议问题