JavaScript多維數(shù)組多鍵值排序方法實現(xiàn)
你對JavaScript實現(xiàn)多維數(shù)組多鍵值排序方法是否熟悉 ,這里和大家分享一下,JavaScript的數(shù)組排序函數(shù)sort方法,默認(rèn)是按照ASCII字符順序進(jìn)行升序排列。
JavaScript實現(xiàn)多維數(shù)組多鍵值排序方法
JavaScript的數(shù)組排序函數(shù)sort方法,默認(rèn)是按照ASCII字符順序進(jìn)行升序排列。
arrayobj.sort(sortfunction);
參數(shù):sortFunction
可選項。是用來確定元素順序的函數(shù)的名稱。如果這個參數(shù)被省略,那么元素將按照ASCII字符順序進(jìn)行升序排列。
sort方法將Array對象進(jìn)行適當(dāng)?shù)呐判?;在?zhí)行過程中并不會創(chuàng)建新的Array對象。
如果為sortfunction參數(shù)提供了一個函數(shù),那么該函數(shù)必須返回下列值之一:
負(fù)值,如果所傳遞的***個參數(shù)比第二個參數(shù)小。
零,如果兩個參數(shù)相等。
正值,如果***個參數(shù)比第二個參數(shù)大。
以上的方法在一維的排序還是很方便的,但像SQL語句中的ORDERBY一樣的多鍵值排序由怎么做呢?
多維數(shù)組的多鍵值排序,則需要復(fù)雜一些,但不需要用循環(huán)解決。實際解決的道理是一樣的。
數(shù)字:
以下的例子是將數(shù)字的多維數(shù)組按照第5列,第9列,第3列的順序排序,像SQL語句中的ORDERBYcol5,col9,col7。數(shù)字的時候可以直接兩個項目相減,以結(jié)果作為返回值即可。
- <scriptlanguagescriptlanguage=javascript>
- varmyArray=newArray();
- for(vari=0;i<10;i++)...{
- myArray[i]=newArray();
- myArray[i][0]=Math.floor(Math.random()*10);
- myArray[i][1]=Math.floor(Math.random()*10);
- myArray[i][2]=Math.floor(Math.random()*10);
- myArray[i][3]=Math.floor(Math.random()*10);
- myArray[i][4]=Math.floor(Math.random()*10);
- myArray[i][5]=Math.floor(Math.random()*10);
- myArray[i][6]=Math.floor(Math.random()*10);
- myArray[i][7]=Math.floor(Math.random()*10);
- myArray[i][8]=Math.floor(Math.random()*10);
- }
- myArray.sort(function(x,y)...{
- return(x[0]==y[0])?((x[4]==y[4])?(x[8]-y[8]):(x[4]-y[4])):(x[2]-y[2])
- });
- for(vari=0;i<myArray.length;i++)...{
- document.write(myArray[i].join(",")+"<br/>");
- }
- </script>
字符:
字符的時候sortFunction中的項目不能像數(shù)字一樣直接相減,需要調(diào)用
str1.localeCompare(str2)方法來作比較,從而滿足返回值。以下是多維數(shù)組的第1,2列作排序的情況。
- functionsortFunction(array)...{
- returnarray.sort(function(x,y)...{
- return(x[0]==y[0])?(x[1].localeCompare(y[1])):(x[0].localeCompare(y[0]))
- });
- }
因此arrayObject.sort(sortFunction)的排序功能還是很強大的,終于能夠?qū)崿F(xiàn)了SQL語句中的ORDERBY一樣的功能。
【編輯推薦】
- JavaScript數(shù)組元素刪除問題解決方案
- 解析Javascript中replace()方法使用
- C#代碼與JavaScript函數(shù)的相互調(diào)用
- JavaScript函數(shù)中arguments對象
- Javascript中CSS屬性float特殊寫法