简体   繁体   English

有人可以解释一下这个功能是如何工作的吗?

[英]Can someone please explain how this function works?

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;
};

Not quite sure what the last part is doing不太确定最后一部分在做什么

This looks like someone taking up the challenge of "I can do this in one line" , which is a very neat and fun challenge, but has no place in real world code - your coworkers will hate you.这看起来像是有人接受了“我可以在一行中做到这一点”的挑战,这是一个非常巧妙和有趣的挑战,但在现实世界的代码中没有立足之地——你的同事会讨厌你。 So let's expand it into something readable:因此,让我们将其扩展为可读的内容:

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;
};
function shuffle(inputArray) { let i = inputArray.length; while (i) { const j = parseInt(Math.random() * i); // generate random integer smaller than i (Math.random() generates random number between 0 and 1) i = i-1; // swap elements on position i and j const element = inputArray[i]; inputArray[i] = inputArray[j] inputArray[j] = x; } return inputArray; };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有人可以向我解释这个功能是如何工作的吗? - Can someone explain to me how this function works? 有人可以解释一下此递归代码如何工作吗? - Can someone please explain how this recursive code works? 有人可以解释一下我的功能deleteButton(this)吗? - Can someone please explain my function deleteButton(this)? 有人可以向我解释如何将这种递归函数添加到自身中吗? - Can someone explain to me how adding this recursive function to itself works? 有人可以解释为什么文件[“写”]有效吗? - Can someone please explain why document[“write”] works? 有人可以解释一下所有格式化工具在 VS Code 中是如何工作的吗? - Can someone please explain how all the formatting tools works in VS Code? 有人可以向我解释一下该范围如何作用于这种匿名函数数组吗? - Can someone please explain to me how the scope works for this array of anonymous functions? 有人可以解释这段代码是如何工作的吗? - Can someone explain how this code even works? 有人可以解释setInterval计数器的工作原理吗? - Can someone explain how the setInterval counter works? 有人可以解释这个 for 循环是如何工作的吗? - Can someone explain how this for loop works?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM