[英]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.