首页 > 解决方案 > 有人可以解释一下这个功能是如何工作的吗?

问题描述

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

不太确定最后一部分在做什么

标签: javascriptfunction

解决方案


这看起来像是有人接受了“我可以在一条线上完成”的挑战,这是一个非常简洁有趣的挑战,但在现实世界的代码中没有位置——你的同事会讨厌你。所以让我们把它扩展成可读的东西:

function shuffle(o) {
    // iterate over the entire input array "o"
    for(var i = o.length - 1; i; i--) {
      // get the "current" item and save it in variable "x"
      var x = o[i];
      // generate a random number within the bounds of the array
      var j = parseInt(Math.random() * (i + 1));

      // The next two lines essentially swap item[i] and item[j]
      // set the "current" item to a randomly picked item
      o[i] = o[j];
      // put the "current" item in the random position
      o[j] = x;
    }

    return o;
};

推荐阅读