Sorting array using Javascript function - Understanding

后端 未结 2 767
情深已故
情深已故 2021-01-24 06:07

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 t

相关标签:
2条回答
  • 2021-01-24 06:37

    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.

    0 讨论(0)
  • 2021-01-24 06:37

    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

    0 讨论(0)
提交回复
热议问题