function sort1(a,b) { return a - b;}
function sort2(a,b) { return a + b;}
var arr = new Array(2,1,4,3);
document.write(arr+"<br>");
document.write(arr.sort(sort1)+"<br>");
document.write(arr.sort(sort2)+"<br>");
输出是:
2,1,4,3
1,2,3,4
3,1,2,4
我实在不明白了,麻烦大虾给我讲一下那个函数参数到底是怎么使用的呢?
为什么返回a-b就升序,而返回a+b就那样子了啊? 

解决方案 »

  1.   

    sort function 必须返回的三个值是 负数,0,和正数。你的SORT2是不符合逻辑的
      

  2.   


    <script type="text/javascript">function sortNumber(a,b)
    {
    return a - b
    }var arr = new Array(6)
    arr[0] = "10"
    arr[1] = "5"
    arr[2] = "40"
    arr[3] = "25"
    arr[4] = "1000"
    arr[5] = "1"document.write(arr + "<br />")
    document.write(arr.sort(sortNumber))</script>楼主建议一下你运行看看打印出来的
      

  3.   

    按照lz的问题,再拓展下思路。1.-------------------------
    <script type="text/javascript">
    function sort1(a,b) { return a - b;}
    function sort2(a,b) { return a + b;}
    var arr = new Array(2,1,4,3,5);
    document.write(arr+"<br>");
    document.write(arr.sort(sort1)+"<br>");
    document.write(arr.sort(sort2)+"<br>");
    </script>
    结果:
    2,1,4,3,5
    1,2,3,4,5
    3,5,1,2,4
    2---------------------------------------
    <script type="text/javascript">
    function sort1(a,b) { return a - b;}
    function sort2(a,b) { return a + b;}
    var arr = new Array(2,1,4,3,5,6);
    document.write(arr+"<br>");
    document.write(arr.sort(sort1)+"<br>");
    document.write(arr.sort(sort2)+"<br>");
    </script>
    结果:
    2,1,4,3,5,6
    1,2,3,4,5,6
    6,5,3,1,2,4
    =3===================================
    <script type="text/javascript">
    function sort1(a,b) { return a - b;}
    function sort2(a,b) { return a + b;}
    var arr = new Array(2,1,4,3,5,6,7);
    document.write(arr+"<br>");
    document.write(arr.sort(sort1)+"<br>");
    document.write(arr.sort(sort2)+"<br>");
    </script>
    结果:
    2,1,4,3,5,6,7
    1,2,3,4,5,6,7
    6,5,3,7,1,2,4
    ===4================================
    <script type="text/javascript">
    function sort1(a,b) { return a - b;}
    function sort2(a,b) { return a + b;}
    var arr = new Array(2,1,4,3,5,6,7,8);
    document.write(arr+"<br>");
    document.write(arr.sort(sort1)+"<br>");
    document.write(arr.sort(sort2)+"<br>");
    </script>
    结果:
    2,1,4,3,5,6,7,8
    1,2,3,4,5,6,7,8
    6,5,3,7,1,2,4,8
    ====last====================
    <script type="text/javascript">
    function sort1(a,b) { return a - b;}
    function sort2(a,b) { return a + b;}
    var arr = new Array(2,1,4,3,5,6,7,8,9);
    document.write(arr+"<br>");
    document.write(arr.sort(sort1)+"<br>");
    document.write(arr.sort(sort2)+"<br>");
    </script>
    结果:
    2,1,4,3,5,6,7,8,9
    1,2,3,4,5,6,7,8,9
    6,5,3,7,9,1,2,4,8