---
# System prepended metadata

title: array.sort() 排序方法進一步的範例說明

---

# array.sort() 排序方法進一步的範例說明
```
var stringArray = ['Blue', 'Humpback', 'Beluga'];
var numericStringArray = ['80', '9', '700'];
var numberArray = [40, 1, 5, 200];
var mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];

function compareNumbers(a, b) {
  return a - b;
}
```
```
console.log('stringArray:', stringArray.join());
    //'stringArray:' 'Blue,Humpback,Beluga'
    //join後的資料會轉為文字；沒有用任何東西join會自動有逗號在string中區隔
    
console.log('Sorted:', stringArray.sort());
    //'Sorted:' ['Beluga','Blue','Humpback'] 
    //沒給compareFunction的sort，會以字元順序排列
    
----------------------------------------------------------------------

console.log('numberArray:', numberArray.join());
    //'numberArray:''40,1,5,200' 
    //join後將陣列數字轉為string，逗號區格
    
console.log('Sorted without a compare function:', numberArray.sort());
    //'Sorted without a compare function:'[1,200,40,5]
    //將數字以字元順序排列
    
console.log('Sorted with compareNumbers:', numberArray.sort(compareNumbers));
    //'Sorted with compareNumbers:'[1,5,40,200]
    //套用由小到大排列的compareFunction，會將陣列值數字由小到大排列

----------------------------------------------------------------------

console.log('numericStringArray:', numericStringArray.join());
    //'numericStringArray:''80,9,700'
    //join後將陣列數字轉為string，逗號區隔
    
console.log('Sorted without a compare function:', numericStringArray.sort());
    //'Sorted without a compare function:' ['700','80','9']
    //沒有給compareFunction的sort()，以字元順序排列
    
console.log('Sorted with compareNumbers:', numericStringArray.sort(compareNumbers));
    //'Sorted with compareNumbers:'['9','80','700']
    //使用compareFunction，即使是"數字字串"，也會被由小到大排列(但輸出仍是陣列中"數字字串")

----------------------------------------------------------------------

console.log('mixedNumericArray:', mixedNumericArray.join());
    //'mixedNumbericArray:''80,9,700,40,1,5,200'
    //join後陣列中的值(不論是string或number)被組成一組string(數字字串)
    
console.log('Sorted without a compare function:', mixedNumericArray.sort());
    //'Sorted without a compare function:'[1,200,40,5,'700','80','9']
    //沒有compareFunction的sort()以字元數序排列，保留原本陣列中的資料格式
    
console.log('Sorted with compareNumbers:', mixedNumericArray.sort(compareNumbers));
    //'Sorted with compareNumbers:'[1,5,'9',40,'80',200,'700']
    //使用由小到大的compareFunction後，陣列中資料由小到大排列，原始格式不變
```