第一种JavaScript sort() 方法
<a class="btn btn-sm btn-red-hollow attention" id="btnAttent" target="_blank">更多免费教学文章<font color="blue" size="2">请关注这里</font></a>
实例
例子 1
在本例中,我们将创建一个数组,并按字母顺序进行排序:
<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
亲自试一试
例子 2
在本例中,我们将创建一个数组,并按字母顺序进行排序:
<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>
```javascript
输出:
10,5,40,25,1000,1
1,10,1000,25,40,5
请注意,上面的代码没有按照数值的大小对数字进行排序,要实现这一点,就必须使用一个排序函数:
```javascript
<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
网友评论