如果提供的數字在0-9之間,請以文字形式返回。
輸入:1
輸出: “One”
依據題意可整理出以下重點:
function switchItUp(number){
const words = ["Zero","One","Two","Three","Four", "Five","Six","Seven","Eight","Nine"];
return words[number];
}
一開始沒有思考到 0,又導致報錯 OTZ
更加精簡的寫法
function switchItUp(number){
return ["Zero","One","Two","Three","Four", "Five","Six","Seven","Eight","Nine"][number];
}
假設題目有限定文字給予的是字串,將字串轉為陣列的 split()
方法就蠻好用的~
function switchItUp(number){
return "Zero One Two Three Four Five Six Seven Eight Nine".spilt(" ")[number];
}
split()
方法split(separator, limit)
,也可以僅帶入 separator
參數separator
:代表的是分割的依據,假設寫入 split(" ")
,就會以空格來分割字串,並組成陣列,且空格不會出現在結果中limit
:限制返回的元素數量const words = "Zero One Two Three Four Five Six Seven Eight Nine";
console.log(words.split(" ", 3)); //["Zero","One","Two"]
Q. 如果是空字串,又或是分割依據不存在呢?
會返回原始字串
const str = "";
console.log(str.split("a")); //""
今天就介紹到這裡,如果大家有更好的寫法歡迎一起來討論哦~