Sorting array using Javascript function - Understanding

会有一股神秘感。 提交于 2019-12-02 06:00:23

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.

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

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