這次的內容是利用作者給的list範例去做排序,若開頭是a |the |an則無視此單字,並且以無視後的第一個字母作為排序[A-Z]
作品實做
removeStart(*e*)
函式將開頭為a|the|an的單字刪除removeStart(*e*)
函式將開頭為a|the|an的單字刪除 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",
];
function removeStart(str) {
return str.replace(/^(a |the |an )/i, "").trim();
}
removeStart(e)
將字串開頭帶有a |the |an
(不限大小寫)的字符消去,並且移除字串起始及結尾處的空白字元
let sortBands = bands.sort((a, b) =>
removeStart(a) > removeStart(b) ? 1 : -1
);
sortBands
將bands用sort()做排序,利用removeStart(e)
帶入參數a,b(字典順序比較)
當removeStart(a)>removeStart(b)
,a應該排在b後面
document.querySelector("#bands").innerHTML = sortedBands
.map((band) => `<li>${band}</li>`)
.join("");
將sortedBands
中的每個元素作為li
渲染在畫面上