当前位置: 首页 > 网络学院 > 客户端脚本教程 > JavaScript > JavaScript sort()方法

JavaScript
JS 介绍
JS 怎样使用
JS 在哪使用
JS 变量
JS If...Else
JS Switch
JS 操作符
JS Popup Boxes
JS 函数
JS For 循环
JS While 循环
JS Break 循环
JS For...In
JS 事件
JS Try...Catch
JS Throw
JS onerror
JS 特殊字符
JS Guidelines
JS 对象介绍

JavaScript sort()方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-03-04   浏览: 346 ::
收藏到网摘: n/a

Definition and Usage
定义与用法

The sort() method is used to sort the elements of an array.
sort()方法可用来排列数组中的元素

Syntax
语法

arrayObject.sort(sortby)

Parameter
参考
Description
描述
sortby Optional. Specifies the sort order. Must be a function
可选项。指定排列次序。必须是一个函数


Tips and Notes
提示与注意点

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()方法后,数组就会改变


Example
举例

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>

The output of the code above will be:
输出的结果为:

Jani,Hege,Stale,Kai Jim,Borge,Tove
Borge,Hege,Jani,Kai Jim,Stale,Tove


Example
举例

In this example we will create an array containing numbers and sort it:
这个举例中我们建立了一个数组,里面包含了数字,我们要排列它:

<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>

The output of the code above will be:
输出的结果是这样:

10,5,40,25,1000,1
1,10,1000,25,40,5

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)
{
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>

The output of the code above will be:
输出结果就为这样了:

10,5,40,25,1000,1
1,5,10,25,40,1000


Try-It-Yourself Demos
尝试与演示

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()来排列数组中的数字?

评论 (0) All

登陆 | 还没注册?