陣列排序,你可以直接呼叫javascript原生自帶的sort()方法,比如下面的例子:
// Array.prototype.sort() //原生自帶的陣列的排序方法;
var fruit = ["apples", "bananas", "Cherries"]; //定義一個數組
fruit.sort(); // ["Cherries", "apples", "bananas"]; //按字母排序的結果
var scores = [1, 2, 10, 21]; //定義一個數字排序,你發現其實還是按照字母序排列的
scores.sort(); // [1, 10, 2, 21]
如果希望按照期望的數字排序。
scores.sort(function(a,b){return a-b}); //這樣的就可以了。結果為:21 10 2 1
var things = ["word", "Word", "1 Word", "2 Words"];
things.sort(); // ["1 Word", "2 Words", "Word", "word"]
// In Unicode, numbers come before upper case letters,
// which come before lower case letters.
陣列排序,你可以直接呼叫javascript原生自帶的sort()方法,比如下面的例子:
// Array.prototype.sort() //原生自帶的陣列的排序方法;
var fruit = ["apples", "bananas", "Cherries"]; //定義一個數組
fruit.sort(); // ["Cherries", "apples", "bananas"]; //按字母排序的結果
var scores = [1, 2, 10, 21]; //定義一個數字排序,你發現其實還是按照字母序排列的
scores.sort(); // [1, 10, 2, 21]
如果希望按照期望的數字排序。
scores.sort(function(a,b){return a-b}); //這樣的就可以了。結果為:21 10 2 1
var things = ["word", "Word", "1 Word", "2 Words"];
things.sort(); // ["1 Word", "2 Words", "Word", "word"]
// In Unicode, numbers come before upper case letters,
// which come before lower case letters.