js 自帶的sort() 方法全面了解
1. 方法概述
Array的sort()方法默認(rèn)把所有元素先轉(zhuǎn)換為String再根據(jù)Unicode排序,
sort()會(huì)改變?cè)瓟?shù)組,并返回改變(排序)后的數(shù)組 。
2. 例子
2.1
如果沒有提供自定義的方法, 數(shù)組元素會(huì)被轉(zhuǎn)換成字符串,并返回字符串在Unicode編碼下的順序比較結(jié)果
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來(lái)排序
// 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() 方法全面了解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
window.showModalDialog參數(shù)傳遞中含有特殊字符的處理方法
程序運(yùn)行出錯(cuò)經(jīng),過檢查發(fā)現(xiàn)傳遞的數(shù)據(jù)中出現(xiàn)了#等特殊字符,瀏覽器只取到#號(hào)前面的數(shù)據(jù),后面的被截?cái)?,下面為大家介紹下正確的處理方法2013-06-06JS實(shí)現(xiàn)樹形結(jié)構(gòu)與數(shù)組結(jié)構(gòu)相互轉(zhuǎn)換并在樹形結(jié)構(gòu)中查找對(duì)象
這篇文章介紹了JS實(shí)現(xiàn)樹形結(jié)構(gòu)與數(shù)組結(jié)構(gòu)相互轉(zhuǎn)換并在樹形結(jié)構(gòu)中查找對(duì)象的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06第四篇Bootstrap網(wǎng)格系統(tǒng)偏移列和嵌套列
這篇文章主要介紹了Bootstrap網(wǎng)格系統(tǒng)偏移列和嵌套列的相關(guān)資料,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06JS實(shí)現(xiàn)隨機(jī)抽獎(jiǎng)小功能
這篇文章主要為大家詳細(xì)介紹了JS實(shí)現(xiàn)隨機(jī)抽獎(jiǎng)小功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01javascript實(shí)現(xiàn)倒計(jì)時(shí)N秒后網(wǎng)頁(yè)自動(dòng)跳轉(zhuǎn)代碼
這篇文章主要介紹了javascript實(shí)現(xiàn)倒計(jì)時(shí)N秒后網(wǎng)頁(yè)自動(dòng)跳轉(zhuǎn)代碼,非常的實(shí)用,這里推薦給大家。2014-12-12