javascript数组排序函数
arrayobj.sort(sortfunction);
参数:sortFunction
可选项。是⽤来确定元素顺序的函数的名称。如果这个参数被省略,那么元素将按照 ASCII 字符顺序进⾏升序排列。
sort ⽅法将 Array 对象进⾏适当的排序;在执⾏过程中并不会创建新的 Array 对象。
如果为 sortfunction 参数提供了⼀个函数,那么该函数必须返回下列值之⼀:
负值,如果所传递的第⼀个参数⽐第⼆个参数⼩。
零,如果两个参数相等。
正值,如果第⼀个参数⽐第⼆个参数⼤。
以上的⽅法在⼀维的排序还是很⽅便的,但像SQL语句中的ORDER BY ⼀样的多键值排序由怎么做呢?
多维数组的多键值排序,则需要复杂⼀些,但不需要⽤循环解决。实际解决的道理是⼀样的。
数字:
以下的例⼦是将数字的多维数组按照第5列,第9列,第3列的顺序排序,像SQL语句中的ORDER BY col5,col9,col7。数字的时候可以直接两个项⽬相减,以结果作为返回值即可。
复制代码代码如下:
<script language=javascript>
var myArray = new Array();
for(var i=0;i<10;i++ )...{
myArray[i]=new Array();
myArray[i][0]=Math.floor(Math.random()*10);
myArray[i]=Math.floor(Math.random()*10);
myArray[i]=Math.floor(Math.random()*10);
myArray[i]=Math.floor(Math.random()*10);
myArray[i]=Math.floor(Math.random()*10);
myArray[i]=Math.floor(Math.random()*10);
myArray[i]=Math.floor(Math.random()*10);
myArray[i]=Math.floor(Math.random()*10);
myArray[i]=Math.floor(Math.random()*10);
}
myArray.sort( function(x, y) ...{
return (x[0]==y[0])?((x==y)?(x-y):(x-y)):(x-y)
});
for(var i=0;i<myArray.length;i++ )...{
document.write(myArray[i].join(",") + "<br/>");
}
</script>
javascript数组对象字符:
字符的时候sortFunction中的项⽬不能像数字⼀样直接相减,需要调⽤
str1.localeCompare( str2 )⽅法来作⽐较,从⽽满⾜返回值。以下是多维数组的第1,2列作排序的情况。
复制代码代码如下:
function sortFunction(array) ...{
return array.sort( function(x, y) ...{
return (x[0]==y[0])?(x.localeCompare(y)):(x[0].localeCompare(y[0]))
});
}
因此arrayObject.sort( sortFunction )的排序功能还是很强⼤的,终于能够实现了SQL语句中的ORDER BY ⼀样的功能。