js对数组中的数字从小到大排序
例子 1
In this example we will create an array and sort it alphabetically:
<script type="text/javascript">var arr = new Array(6)arr[0] = "Jani"arr[1] = "Hege"arr[2] = "Stale"arr[3] = "Kai Jim"arr[4] = "Borge"arr[5] = "Tove"document.write(arr + "<br />")document.write(arr.sort())</script>
输出:
Jani,Hege,Stale,Kai Jim,Borge,ToveBorge,Hege,Jani,Kai Jim,Stale,Tove
例子 2
In this example we will create an array and sort it alphabetically:
<script type="text/javascript">var arr = new Array(6)arr[0] = "10"arr[1] = "5"arr[2] = "40"arr[3] = "25"arr[4] = "1000"arr[5] = "1"document.write(arr + "<br />")document.write(arr.sort())</script>
输出:
10,5,40,25,1000,11,10,1000,25,40,5
请注意,上面的代码没有按照数值的大小对数字进行排序,要实现这一点,就必须使用一个排序函数:
<script type="text/javascript">function sortNumber(a,b){return a - b}var arr = new Array(6)arr[0] = "10"arr[1] = "5"arr[2] = "40"arr[3] = "25"arr[4] = "1000"arr[5] = "1"document.write(arr + "<br />")document.write(arr.sort(sortNumber)
)</script>
输出:
10,5,40,25,1000,11,5,10,25,40,1000
TAG: