2014年1月16日 星期四

【Javascript】Array sort() Method

  1. 內建 Array sort
  2. var fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits.sort();
    // output is Apple,Banana,Mango,Orange
    
  3. 內建 reverse
  4. var fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits.sort();
    fruits.reverse();
    // output is Orange,Mango,Banana,Apple
    
  5. Sort numbers (numerically and ascending)
  6. var points = [40,100,1,5,25,10];
    points.sort(function(a,b){return a-b});
    // output is 1,5,10,25,40,100
    
  7. Sort numbers (alphabetically and descending)
  8. var points = [40,100,1,5,25,10];
    points.sort(function(a,b){return b-a});
    // output is 100,40,25,10,5,1
    
    ##### 上述例子為 w3shools Example #####
    ##### 以下是 object sort method #####

  9. object sort numbers
  10. var student = [{name: "Tom", score: 80}
    , {name: "Mary", score: 70}
    , {name: "Cathy", score: 90}];
    student.sort(function(a,b){return a.score-b.score});
    // output is [{name: "Mary", score: 70}, 
    // {name: "Tom", score: 80}, 
    // {name: "Cathy", score: 90}]
    
  11. object sort alphabetically
  12. var student = [{name: "Tom", score: 80}
    , {name: "Mary", score: 70}
    , {name: "Cathy", score: 90}];
    student.sort(function(a,b){return a.name > b.name});
    // output is [{name: "Cathy", score: 90}, 
    // {name: "Mary", score: 70},
    // {name: "Tom", score: 80}]
    

沒有留言:

張貼留言