<html>
<body><script type="text/javascript">function sortNumber(a, b)
{
document.write("a="+a+ " ");
document.write("b="+b+ " ");
document.write("(a-b)="+(a-b)+ "<br />");
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("<br />");
document.write(arr.sort(sortNumber)+ "<br />")</script></body>
</html>这里结果为:a=1 b=40 (a-b)=-39
a=25 b=1000 (a-b)=-975
a=1000 b=5 (a-b)=995
a=1000 b=40 (a-b)=960
a=1000 b=10 (a-b)=990
a=25 b=5 (a-b)=20
a=25 b=10 (a-b)=15
a=25 b=40 (a-b)=-15
a=40 b=1 (a-b)=39
a=25 b=1 (a-b)=24
a=25 b=5 (a-b)=20
a=10 b=5 (a-b)=5
a=10 b=1 (a-b)=9
a=10 b=5 (a-b)=5
a=5 b=1 (a-b)=4
1,5,10,25,40,1000
为什么会是这样子进入该排序函数呢?
十分不解啊!!!
我去看看,初学= =
如果是数字排序或其他特殊排序还要设置相关参数(函数):sort(parameters)。下面是一些不同情况下的函数扩展:
<script type="text/javascript">
//自定义一个数组排序扩展的原型
Array.prototype.sortExt=function(type,str){
switch (type){
case "string":/* 字串顺序*/
this.sort();
return this;
//break;
case "number":/* 数字数组排序*/
this.sort(
function(a,b){
return a-b;
}
);
return this;
case "pinyin":
this.sort(
function(a,b){
return a.localeCompare(b)
}
);
return this;
case "disorder":/* 数组乱序*/
this.sort(
function(){
return Math.random()>0.5?-1:1;
}
);
return this;
case "withsearch":/*带搜索(str为要搜索的字串) 匹配元素排前*/
this.sort(
function(a,b){
return a.indexOf(str)==-1?1:a.localeCompare(b);
}
);
return this;
default: /*(默认)等同于字串数组排序*/
this.sort();
return this;
}
}//-----------
var arr=[];
for(var i=2;i<14;i++){arr.push(i)}var arrCN=Array("哈哈","波","柴科夫斯基","特","啊","这个")
var arrCN=Array("ABOUT","波","柴科夫斯基","111","HELLO","这个")document.write(arr.sortExt('string') + "<br />")
document.write(arr.sortExt('number') + "<br />")
document.write(arrCN.sortExt('pinyin') + "<br />")
document.write(arr.sortExt('disorder') + "<br />")
document.write(arrCN.sortExt('withsearch','哈') + "<br />")</script>