标签:
在本例中,我们将创建一个数组,并按字母顺序进行排序:
<script type="text/javascript">
var arr = new Array(6)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
arr[3] = "James"
arr[4] = "Adrew"
arr[5] = "Martin"
document.write(arr + "<br />")
document.write(arr.sort()
)
</script>
输出:
George,John,Thomas,James,Adrew,Martin Adrew,George,James,John,Martin,Thomas
在本例中,我们将创建一个数组,并按字母顺序进行排序:
<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,1 1,10,1000,25,40,5
请注意,上面的代码没有按照数值的大小对数字进行排序,要实现这一点,就必须使用一个排序函数:
<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,1 1,5,10,25,40,1000
标签:
原文地址:http://www.cnblogs.com/yuwensong/p/5089537.html