以随机顺序对数组排序 [英] Sorting an Array in Random Order

查看:91
本文介绍了以随机顺序对数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何以随机顺序对数组进行排序。因此,我发现了以下代码:

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而不是其他数字
它是如何工作的,请尝试使其变得简单,因为我是javascript的新手,并且正在为这些事情而苦苦挣扎

my main question is why they use 0.5 not another number? and how it really works please try to make it simple i'm new in javascript and i'm struggling with these things

推荐答案

您使用

var as = ["max","jack","sam"];  
var s = as.sort(func);  

function func(a, b) {  
  return 0.5 - Math.random();
}  

console.log(s);

这里最重要的事情 .sort(func)

func(a,b)将返回 [-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].

这意味着排序顺序将设置为增加减少
这是随机的。
所以您的结果将是随机的

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆