当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javascript 数组排序函数

Javascript
Add a Table to a Word Document
Add Formatted Text to a Word Document
用jscript实现新建word文档
用jscript实现新建和保存一个word文档
Open and Print a Word Document
Use Word to Search for Files
Convert Seconds To Hours
Sample script that deletes a SQL Server database
Sample script that displays all of the users in a given SQL Server DB
firefox中用javascript实现鼠标位置的定位
div+css实现鼠标放上去,背景跟图片都会变化。
Locate a File Using a File Open Dialog Box
Save a File Using a File Save Dialog Box
用jscript实现列出安装的软件列表
List the Stored Procedures in a SQL Server database
Display SQL Server Login Mode
Display SQL Server Version Information
List all the Databases on a SQL Server
用jscript启动sqlserver
Stop SQL Server

Javascript 中的 javascript 数组排序函数


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 438 ::
收藏到网摘: n/a

javascript的数组排序函数 sort方法,默认是按照ASCII 字符顺序进行升序排列。 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>

字符:
字符的时候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 一样的功能。