使用Javascript函数对数组进行排序-了解 [英] Sorting array using Javascript function - Understanding
问题描述
我决定从数组中获取改组后的值.为此,我使用了此功能,我从网上得到了它,效果很好.但是我不知道它是如何工作的...
I decided to get shuffled values from array. for that i used this function, i got it from net, it works fine. But i don't know, how it's works...
任何人都可以帮助我理解这一点吗?
any one can help me to understand this?
我的代码是:
function rand(ar){
return 0.5-Math.random();
}
var ar = [5,10,15,20,25]
ar.sort(rand);
console.log(ar)
我正在使用此函数从声明的值中获取新的改组数组值.
I am using this function for getting new shuffled array values from the declared one.
推荐答案
此代码使用提供的rand
函数作为Array.Sort
方法的比较运算符( http://msdn.microsoft.com/en-us /library/41336409.aspx )函数返回的值从0(包括)到1(不包括),rand
函数的返回值从0.5(包括)到-0.5(不包括).
This code is using the supplied rand
function as the comparison operator for the Array.Sort
method (http://msdn.microsoft.com/en-us/library/4b4fbfhk(VS.85).aspx). Since the Math.random (http://msdn.microsoft.com/en-us/library/41336409.aspx) function returns a value from 0 (inclusive) to 1 (exclusive), the rand
function will return a value from 0.5 (inclusive) to -0.5 (exclusive).
通常,提供给Sort
方法的sortFunction接受2个参数进行比较. sortFunction比较它们并返回一个值,该值表示:
Normally the sortFunction supplied to the Sort
method takes 2 arguments that are compared. The sortFunction compares them and returns a value that means:
- 负数-第一项小于第二项
- 零-项目相等
- 正面-第一项大于第二项
sort
方法运行时,它使用此比较来确定哪些数组值应位于其他值之前.
As the sort
method runs, it uses this comparison to determine which array values should go before the others.
对于您的代码,rand
函数的返回值是随机的,并且与数据无关.这意味着,每当sort
函数尝试比较数组中的两个值时,一半的时间会说第一项小于第二项,而第二项的一半将小于第一项.在阵列的整个长度上完成此操作后,项目将随机交换,整个阵列将变得随机化.
In the case of your code, the rand
function's return value is random and has no correlation to the data. This means that, whenever the sort
function tries to compare two values in the array, half of the time it will say the first item is less than the second and half the second item will be less than the first. As this is done over the entire length of the array, items are swapped randomly and the whole array becomes randomized.
这篇关于使用Javascript函数对数组进行排序-了解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!