JavaScript数组有个sort方法可以排序,但都是转换成字符串进行比较的,如果数组中全为数字怎么才能按数字大小进行比较?
如 var aArray=[1,3,5,7,2,4,6,8];
排序后想得到 aArray=[1,2,3,4,5,6,7,8];
<html>
<head>
<title>数组对象的sort()方法</title>
<script language="javascript" type="text/javascript">
<!--
var arr = [39,11,3,9,1,77];
document.write("原数组元素为:" + arr.toString() + "<br>");
arr.sort();
document.write("按字符编码排序:" + arr.toString() + "<br>");
//正序排序
function ascOrder(x,y)
{
if (x>y)
{
return 1;
}
else
{
return -1;
}
}
//倒序排序
function descOrder(x,y)
{
if (x>y)
{
return -1;
}
else
{
return 1;
}
}
arr.sort(ascOrder);
document.write("按数字正序排序:" + arr.toString() + "<br>");
arr.sort(descOrder);
document.write("按数字倒序排序:" + arr.toString() + "<br>");
-->
</script>
</head>
<body>
</body>
</html>