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
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
請注意,上面的代碼沒有按照數(shù)值的大小對數(shù)字進(jìn)行排序,要實(shí)現(xiàn)這一點(diǎn),就必須使用一個排序函數(shù):
<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