最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

Day 17 – Sort Without Articles

XAMPP下载 admin 673浏览 0评论
 今天要做的是排序,但不同於一般排序這次要忽略冠詞(a, an, the)之後才做排序

首先有一未經排序的 array

const bands = [‘The Plot in You’, ‘The Devil Wears Prada’, ‘Pierce the Veil’, ‘Norma Jean’, ‘The Bled’, ‘Say Anything’, ‘The Midway State’, ‘We Came as Romans’, ‘Counterparts’, ‘Oh, Sleeper’, ‘A Skylit Drive’, ‘Anywhere But Here’, ‘An Old Dog’];
sort(..)
開始之前先複習一下 sort(..):如果括號內不填入任何內容,JS 會依照預設方式排序

數字:前後像的第一位、第二位…相比,如要依照大小排序,則要寫成
[111, 312, 2000].sort();  // [111, 312, 2000]
[111, 312, 2000].sort((a, b) => a – b);  // [111, 312, 2000]
字串:前後像的第一位、第二位… 的 unicode 相比(中文也可以)
[‘an apple’, ‘the game’, ‘pikachu’].sort();  // [‘an apple’, ‘picachü’, ‘the game’]
至於要怎麼忽略冠詞做排序就是今天的主題了!

為了要忽略冠詞不計,我們用正則表達式(Regular Expression)來實作,規則是當開頭是 the, a, the 時將其取代成空 string

function strip(band) {
return band.replace(/^(the |a |an /i), ”).trim();
}
使用 trim() 是避免轉完之後兩側會有空格

接著就可以進入 sort() 做排序了

const sortedBands = bands.sort(function(a, b) {
if (strip(a) > strip(b)) {
return 1;
} else {
return -1;
}
});
或是用 ES6 Arrow Function 寫

const sortedBands = bands.sort((a, b) => strip(a) > strip(b)? 1 : -1);
這樣就排序完成了!接著再印到頁面

document.querySelector(‘#bands’).innerHTML = sortedbands.map(band => `<li>${band}<>`).join(”);
今天練習一開始沒有想到使用正則表達式,結果寫了一堆又糙又複雜的程式碼,使用後才驚覺原來可以寫得這麼簡單。結論是正則表達式必須好好學,可以省去很多不必要的麻煩。

转载请注明:XAMPP中文组官网 » Day 17 – Sort Without Articles

您必须 登录 才能发表评论!