jquery Sort函数
2014-02-07 19:45
423 查看
Example
Sort an array:var fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.sort();The result of fruits will be:Apple,Banana,Mango,Orange
Definition and Usage
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.Browser Support
The sort() method is supported in all major browsers.
Syntax
array.sort(sortfunction)Parameter Values
Parameter | Description |
---|---|
sortfunction | Optional. A function that defines the sort order |
Return Value
Type | Description |
---|---|
Array | The Array object, with the items sorted |
Technical Details
JavaScript Version: | 1.1 |
---|
More Examples
Example
Sort numbers (numerically and ascending):var points = [40,100,1,5,25,10];points.sort(function(a,b){return a-b});
The result of points will be:1,5,10,25,40,100
Example
Sort numbers (numerically and descending):var points = [40,100,1,5,25,10];points.sort(function(a,b){return b-a});
The result of points will be:100,40,25,10,5,1
Example
Sort numbers (alphabetically and descending):var fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.sort();
fruits.reverse();The result of fruits will be:Orange,Mango,Banana,Apple
实例:
<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
相关文章推荐
- Jquery重新学习之六[操作XML数据]
- jQuery.extend 函数详解
- jQuery 插件开发
- JQuery插件的写法和规范
- jquery控制页面元素跟随滚动
- JQuery元素选择
- 【jquery】之touchstart和mousedown
- jquery-mobile中data-role='collapsible'动态加载数据后,折叠组样式丢失
- 编写更好的jQuery代码的建议
- 黑马程序员--JQuery学习笔记
- 编写更好的jQuery代码的建议
- jquery操作select(取值,设置选中)
- jQuery.extend 函数详解
- jquery循环下拉框中所有的值
- 关于jquery动态添加的新元素无法绑定事件那些事
- jquery圆角插件
- jquery datatables
- jquery键盘事件全记录
- jQuery获取当前对象标签名称的方法
- 【jquery】插件之position与offset