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

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

這看起來像是有人接受了“我可以在一行中做到這一點”的挑戰,這是一個非常巧妙和有趣的挑戰,但在現實世界的代碼中沒有立足之地——你的同事會討厭你。 因此,讓我們將其擴展為可讀的內容:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM