js对数组中的数字从⼩到⼤排序例⼦ 1
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>
输出:
Jani,Hege,Stale,Kai Jim,Borge,Tove
Borge,Hege,Jani,Kai Jim,Stale,Tove
例⼦ 2
In this example we will create an array and sort it alphabetically:
<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 />")
sort函数 jsdocument.write(arr.sort(sortNumber))
</script>
输出:
10,5,40,25,1000,1
1,5,10,25,40,1000
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论