我非常接近完成這個練習。指令是將 str 轉換為這個新的 string Here Is My Handle Here Is My Spout。
我的代碼正在準確回傳,Here Is My Handle Here Is My Spout但是當我嘗試回傳時,console.log(result.split(" "))它與 this 一起回傳[ '', 'Here', 'Is', 'My', 'Handle', 'Here', 'Is', 'My', 'Spout' ] 。
我試圖擺脫索引 0 中的空字串,但我似乎無法洗掉它。我還想當words我將它傳遞給result而不是字串時,我正在回傳陣列?
function titleCase(str) {
const words = str.toLowerCase().split(" ");
let result = "";
for (let word of words) {
let firstCap = word.replace(word[0], word[0].toUpperCase());
result = result " " firstCap;
}
console.log(result.split(" "))
return result;
}
console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));
uj5u.com熱心網友回復:
問題出在這條線上:
result = result " " firstCap;
當result有值時"",您不應該添加空格,而是添加一個空字串,如下所示:
result = result (result.length ? " " : "") firstCap;
function titleCase(str) {
const words = str.toLowerCase().split(" ");
let result = "";
for (let word of words) {
let firstCap = word.replace(word[0], word[0].toUpperCase());
result = result (result.length ? " " : "") firstCap;
}
console.log(result.split(" "))
return result;
}
console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));
更好的方法是使用Array#map()后跟Array#join().
function titleCase(str) {
const words = str.toLowerCase().split(" ");
return words.map(word => word.replace(word[0], word[0].toUpperCase())).join(" ");
}
console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/445068.html
標籤:javascript 数组 for循环
上一篇:如何加快PandasDataframe上的“for”回圈
下一篇:我怎樣才能對這個陣列進行排序?
