1. 方法概述
Array的sort()方法默認把所有元素先轉換為String再根據Unicode排序,
sort()會改變原數組,並返回改變(排序)後的數組 。
2. 例子
2.1
如果沒有提供自定義的方法, 數組元素會被轉換成字符串,並返回字符串在Unicode編碼下的順序比較結果
var fruit = ['cherries', 'apples', 'bananas']; fruit.sort(); // ['apples', 'bananas', 'cherries'] var scores = [1, 10, 2, 21]; scores.sort(); // [1, 10, 2, 21] // Watch out that 10 comes before 2, // because '10' comes before '2' in Unicode code point order. 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.
2.2 利用map來排序
// the array to be sorted var list = ['Delta', 'alpha', 'CHARLIE', 'bravo']; // temporary array holds objects with position and sort-value var mapped = list.map(function(el, i) { return { index: i, value: el.toLowerCase() }; }) // sorting the mapped array containing the reduced values mapped.sort(function(a, b) { return +(a.value > b.value) || +(a.value === b.value) - 1; }); // container for the resulting order var result = mapped.map(function(el){ return list[el.index]; }); alert(result);
參考 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
以上這篇js 自帶的sort() 方法全面了解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持。