sort() 方法用于对数组进行排序
语法使用
String[] s={"tom","many","jet","jack"}
Arrays.sort(s)
得到的结果是 s={"jack","jet","many","tom"}
以字母顺序进行排序(按照字符编码的顺序作为排序)
var arr = new Array(6) arr[0] = "100" arr[1] = "5" arr[2] = "41" arr[3] = "35" arr[4] = "1000" arr[5] = "1"
得到的结果是 1 100 1000 35 41 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
具有字母和数字的排序
var strArr = ['a', '2', 'a2', '2a', 'b', '3'];
alert(strArr.sort());
得到的结果是 2 2a 3 a a2 b(因为数字的ascii码比字母小,所以数字排在前面)