參數(shù):sortFunction
可選項(xiàng)。是用來確定元素順序的函數(shù)的名稱。如果這個(gè)參數(shù)被省略,那么元素將按照 ASCII 字符順序進(jìn)行升序排列。
sort 方法將 Array 對(duì)象進(jìn)行適當(dāng)?shù)呐判颍辉趫?zhí)行過程中并不會(huì)創(chuàng)建新的 Array 對(duì)象。
如果為 sortfunction 參數(shù)提供了一個(gè)函數(shù),那么該函數(shù)必須返回下列值之一:
負(fù)值,如果所傳遞的第一個(gè)參數(shù)比第二個(gè)參數(shù)小。
零,如果兩個(gè)參數(shù)相等。
正值,如果第一個(gè)參數(shù)比第二個(gè)參數(shù)大。
以上的方法在一維的排序還是很方便的,但像SQL語句中的ORDER BY 一樣的多鍵值排序由怎么做呢?
多維數(shù)組的多鍵值排序,則需要復(fù)雜一些,但不需要用循環(huán)解決。實(shí)際解決的道理是一樣的 。
數(shù)字:
以下的例子是將數(shù)字的多維數(shù)組按照第5列,第9列,第3列的順序排序,像SQL語句中的ORDER BY col5,col9,col7。數(shù)字的時(shí)候可以直接兩個(gè)項(xiàng)目相減,以結(jié)果作為返回值即可。
復(fù)制代碼 代碼如下:
<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>
字符:
字符的時(shí)候sortFunction中的項(xiàng)目不能像數(shù)字一樣直接相減,需要調(diào)用
str1.localeCompare( str2 )方法來作比較,從而滿足返回值。以下是多維數(shù)組的第1,2列作排序的情況。
復(fù)制代碼 代碼如下:
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 )的排序功能還是很強(qiáng)大的,終于能夠?qū)崿F(xiàn)了SQL語句中的ORDER BY 一樣的功能。
JavaScript技術(shù):javascript 數(shù)組排序函數(shù),轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。