当前位置: 首页 > 网络学院 > 客户端脚本教程 > JavaScript > JavaScript sort()方法
The sort() method is used to sort the elements of an array.
sort()方法可用来排列数组中的元素
arrayObject.sort(sortby) |
Parameter 参考 | Description 描述 |
---|---|
sortby | Optional. Specifies the sort order. Must be a function 可选项。指定排列次序。必须是一个函数 |
Note: The sort() method will sort the elements alphabetically by default. However, this means that numbers will not be sorted correctly (40 comes before 5). To sort numbers, you must create a function that compare numbers.
注意点:sort()方法的默认排列次序是按字母大小排列。这就意味着数字的排列就会不太准确(40会在5的前面显示)。如要排列数字,你就必须建立函数来比较数字
Note: After using the sort() method, the array is changed.
注意:使用sort()方法后,数组就会改变
In this example we will create an array and sort it alphabetically:
在这个举例中我们将建立起一个数组,并且它是按字母大小顺序排列的:
<script type="text/javascript"> var arr = new Array(6) document.write(arr + "<br />") </script> |
The output of the code above will be:
输出的结果为:
Jani,Hege,Stale,Kai Jim,Borge,Tove |
In this example we will create an array containing numbers and sort it:
这个举例中我们建立了一个数组,里面包含了数字,我们要排列它:
<script type="text/javascript"> var arr = new Array(6) document.write(arr + "<br />") </script> |
The output of the code above will be:
输出的结果是这样:
10,5,40,25,1000,1 |
Note that the numbers above are NOT sorted correctly (by numeric value). To solve this problem, we must add a function that handles this problem:
可以注意到数字部分的排列并不是按数字的大小来排列的。要解决这个问题,我们就必须加入一个函数来处理它:
<script type="text/javascript"> function sortNumber(a,b) var arr = new Array(6) document.write(arr + "<br />") </script> |
The output of the code above will be:
输出结果就为这样了:
10,5,40,25,1000,1 |
sort() alphabetically
How to use sort() to sort an array alphabetically.
怎样使用sort()来将数组进行字母大小排列?
sort() by number
How to use sort() to sort an array by number.
怎样使用sort()来排列数组中的数字?