Sort an array:
The result of fruits will be:
The sort() method sorts the items of an array.
The sort order can be either alphabetic or numeric, and either ascending or descending.
Default sort order is alphabetic and ascending.
Note: When numbers are sorted alphabetically, "40" comes before "5".
To perform a numeric sort, you must pass a function as an argument when calling the sort method.
The function specifies whether the numbers should be sorted ascending or descending.
It can be difficult to understand how this function works, but see the examples at the bottom of this page.
Note: This method changes the original array.
The sort() method is supported in all major browsers.
Parameter | Description |
---|---|
sortfunction | Optional. A function that defines the sort order |
Type | Description |
---|---|
Array | The Array object, with the items sorted |
JavaScript Version: | 1.1 |
---|
Sort numbers (numerically and ascending):
The result of points will be:
Sort numbers (numerically and descending):
The result of points will be:
Sort numbers (alphabetically and descending):
The result of fruits will be:
实例:
<p id="demo">Click the button to sort the array.</p>
<button it</button>
<script>
function myFunction()
{
var c_s=['2013-08','2013-07','2013-05','2013-09'];
var a=c_s.sort(function (a, b) {return a<b; });
var x=document.getElementById("demo");
x.innerHTML=a;
}
</script>
字符类型数组,用"return a-b"无法实现排序,用"return a>b"
数值类型数组,用"return a-b"、"return a>b"都能实现排序
当“return a<b;”时,按降序排列,结果为 2013-09,2013-08,2013-07,2013-05
当“return a>b;”时,按升序排列,结果为 2013-05,2013-07,2013-08,2013-09