码迷,mamicode.com
首页 > 编程语言 > 详细

关于sort排序

时间:2017-01-06 22:18:10      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:asc   方便   sql语句   int   对象   document   数字   return   不能   

JavaScript的数组排序函数 sort方法,默认是按照ASCII 字符顺序进行升序排列。
arrayobj.sort(sortfunction);
参数:sortFunction
可选项。是用来确定元素顺序的函数的名称。如果这个参数被省略,那么元素将按照 ASCII 字符顺序进行升序排列。
sort 方法将 Array 对象进行适当的排序;在执行过程中并不会创建新的 Array 对象。
如果为 sortfunction 参数提供了一个函数,那么该函数必须返回下列值之一:
负值,如果所传递的第一个参数比第二个参数小。
零,如果两个参数相等。
正值,如果第一个参数比第二个参数大。
通过实际例子来了解sort函数
1.字符串排序

  var fruits = ["Banana""Orange""Apple""Mango"]
  fruits.sort()//排序结果是Apple,Banana,Mango,Orange 
  //若要得到结果Orange,Mango,Banana,Apple只需要将上步得到的fruits结果反转即可 

  fruits.reverse();//排序结果是Orange,Mango,Banana,Apple

2.数字排序
  
 从小到大
 var points = [40,100,1,5,25,10]
 points.sort(function(a,b){return a-b})//排序结果是1,5,10,25,40,100

从大到小
var points = [40,100,1,5,25,10]
points.sort(function(a,b){return b-a})//排序结果是100,40,25,10,5,1

      以上的方法在一维的排序还是很方便的,但像SQL语句中的ORDER BY 一样的多键值排序由怎么做呢?
多维数组的多键值排序,则需要复杂一些,但不需要用循环解决。实际解决的道理是一样的 。
数字:

以下的例子是将数字的多维数组按照第3列,像SQL语句中的ORDER BY col。数字的时候可以直接两个项目相减,以结果作为返回值即可。

<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][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[2]-y[2]) 
    })

    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[1].localeCompare(y[1])):(x[0].localeCompare(y[0])) 
    })

}

关于sort排序

标签:asc   方便   sql语句   int   对象   document   数字   return   不能   

原文地址:http://www.cnblogs.com/shpxhk/p/6257192.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!