Sorting array using Javascript function - Understanding

南楼画角 提交于 2019-12-02 12:56:04

问题


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?

my code is :

  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.


回答1:


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).

Normally the sortFunction supplied to the Sort method takes 2 arguments that are compared. The sortFunction compares them and returns a value that means:

  • Negative - The first item is less than the second
  • Zero - The items are equal
  • Positive - The first item is greater than the second

As the sort method runs, it uses this comparison to determine which array values should go before the others.

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.




回答2:


array.sort() has an optional parameter that is a sorting function, you can pass a function reference to change the order of the array.

Maybe this page can be helpful http://www.javascriptkit.com/javatutors/arraysort.shtml



来源:https://stackoverflow.com/questions/7802661/sorting-array-using-javascript-function-understanding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!