以随机顺序对数组进行排序 [英] Sorting an Array in Random Order
问题描述
我试图了解以随机顺序对数组进行排序的工作原理.所以,我找到了以下代码:
I'm trying to understand how sorting an array in random order works. So, I found the following code:
var as = ["max","jack","sam"];
var s = as.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
console.log(s);
我的主要问题是为什么他们使用0.5 而不是另一个数字?以及它是如何工作的
my main question is why they use 0.5 not another number? and how it really works
推荐答案
你用过
var as = ["max","jack","sam"];
var s = as.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
console.log(s);
而且这里最重要的事情是as.sort(func)
.func(a,b)
将返回 [-0.5,0.5]
范围内的值.
And here the most important thing is as.sort(func)
.
func(a,b)
will return value in range of [-0.5,0.5]
.
因为这个函数返回0.5 - Math.random()
而Math.random()
将返回[0,1]
.
这样您的 func
将返回 [-0.5,0.5]
范围内的值.
Because this function return 0.5 - Math.random()
and Math.random()
will return the float value which is in range of [0,1]
.
So that your func
will return value in range of [-0.5,0.5]
.
这意味着排序顺序将设置为increase
或decrease
.这是随机的.所以你的结果将是随机的
And this mean that sort order will be set increase
or decrease
.
this is random.
So your result will be random
var as = ["max","jack","sam"];
var s = as.sort(func);
function func(a, b) {
return Math.random();
}
console.log(s);
var as = ["max","jack","sam"];
var s = as.sort(func);
function func(a, b) {
return 0 - Math.random();
}
console.log(s);
var as = ["max","jack","sam"];
var s = as.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
console.log(s);
这篇关于以随机顺序对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!