- 內建 Array sort
- 內建 reverse
- Sort numbers (numerically and ascending)
- Sort numbers (alphabetically and descending)
- object sort numbers
- object sort alphabetically
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); // output is Apple,Banana,Mango,Orange
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); fruits.reverse(); // output is Orange,Mango,Banana,Apple
var points = [40,100,1,5,25,10]; points.sort(function(a,b){return a-b}); // output is 1,5,10,25,40,100
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 #####
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}]
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}]
沒有留言:
張貼留言