JS30~這次的主題是排序,也是一個相對單純的主題,sort在JS中是個很實用、同時也很不直觀的函數(相較其他程式語言來說),初次使用恐怕都會有些迷惑。這次的主題除了基本的sort使用,更加入了一點小小的twist! 要求你排序樂團的名單,但排序時需要忽略a the an 等相對不重要的字~!
腦中有想法了嗎? 一起來看看吧!
HTML
<ul id="bands"></ul>
CSS
body {
margin: 0;
font-family: sans-serif;
background: url("https://source.unsplash.com/nDqA4d5NL0k/2000x2000");
background-size: cover;
display: flex;
align-items: center;
min-height: 100vh;
}
#bands {
list-style: inside square;
font-size: 20px;
background: white;
width: 500px;
margin: auto;
padding: 0;
box-shadow: 0 0 0 20px rgba(0, 0, 0, 0.05);
}
#bands li {
border-bottom: 1px solid #efefef;
padding: 20px;
}
#bands li:last-child {
border-bottom: 0;
}
a {
color: #ffc600;
text-decoration: none;
}
Javascript
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'];
//建立排序後的陣列
const sortedBands = bands.sort((a, b) => {
return strip(a) > strip(b) ? 1 : -1
})
//建立排序忽略a the an 的功能,此處用了regrex
function strip(text) {
return text.replace(/^(a |the|an )/i, '').trim()
}
//利用map&join將陣列推進清單內
document.querySelector('#bands').innerHTML =
sortedBands.map(item => `<li>${item}</li>`
).join('')
學習重點
- 複習regrex & replace的使用,這東西久沒用真的會忘記
- 再一次複習map配合join連接的作法
- 複習sort的用法
- 複習template iteral
最終成品
