search

Home  >  Q&A  >  body text

javascript - How to understand sort in array arrangement

        var fruit=[7,10,32,6,9,4];
        document.write(fruit+'<br>');
        fruit.sort(sortFun);
        document.write(fruit);
        function sortFun(ar1,ar2){
            if(ar1>ar2){
                return 1;
            }else if(ar1<ar2){
                return -1;
            }else{
                return 0;
            }
        }

How does this code arrange the array elements? Please give me a detailed explanation. Thank you.

PHPzPHPz2746 days ago616

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-05-19 10:13:03

    To help you understand, you can try calling the sort method directly:

    var fruit=[7,10,32,6,9,4];
    fruit.sort();

    The return result is: [10, 32, 4, 6, 7, 9]
    而不是期待中的:[ 4, 6, 7, 9, 10, 32]

    Why is this happening?
    Because this is the sort() method on the array prototype chain, which is Array.prototype.sort().

    How to study this sort() method in depth:
    1. You can go to the mdn document https://developer.mozilla.org...
    2. You can go to "Javascript Advanced Programming", but the advanced design is not complete
    3. The most violent way is to read the ECMA2015 specifications: http://www.ecma-international...
    4. If you really feel it’s a headache, you can read the blog I wrote last year and repeat 1,2 , 3 steps: http://www.jianshu.com/p/b50a...
    Hope it can help you...

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-19 10:13:03

     fruit.sort(sortFun);
    
    sort 数组的排序方法;
     用法:
            var arr=[]; 
            arr.sort(function(a,b){
                
            })
            比如从小到大:
            var arr=[9,5,6]; 
            arr.sort(function(a,b){
                return a-b;
            })
            
           fruit.sort(sortFun);中的sortFun就相当于arr.sort(function(a,b){})
           中的function(a,b){};
           if(ar1>ar2){
                    return 1;
                }else if(ar1<ar2){
                    return -1;
                }else{
                    return 0;
                }就相当于return a-b;

    reply
    0
  • 为情所困

    为情所困2017-05-19 10:13:03

    You may need this article https://developer.mozilla.org...

    reply
    0
  • Cancelreply