我有一組小函式,它們共同將給定的字串從 underscore_case 轉換為 camelCase。這是我的代碼片段:
function splitStr(str) {
return str.split('_');
}
function checkStrPosZero(strArr, str) {
return !strArr.indexOf(str);
}
function editStrIfFalse(zero, str) {
if (zero) return str;
let returnStr = '';
for (const char of str)
if (checkStrPosZero(str, char)) returnStr = char.toUpperCase();
else returnStr = char;
return returnStr;
}
function loopStrArrAndCamelify(str) {
let returnStr = '';
for (const char of splitStr(str))
returnStr = editStrIfFalse(checkStrPosZero(splitStr(str), char));
return returnStr;
}
console.log(loopStrArrAndCamelify('hello_world'));
出于某種原因,我收到一條錯誤訊息,指出該str變數不是可迭代的,這沒有意義,就像str字串一樣。很困惑,所以任何幫助表示贊賞。
uj5u.com熱心網友回復:
您缺少editStrIfFalse(). 所以str默認為undefined,這是不可迭代的。
function splitStr(str) {
return str.split('_');
}
function checkStrPosZero(strArr, str) {
return !strArr.indexOf(str);
}
function editStrIfFalse(zero, str) {
if (zero) return str;
let returnStr = '';
for (const char of str)
if (checkStrPosZero(str, char)) returnStr = char.toUpperCase();
else returnStr = char;
return returnStr;
}
function loopStrArrAndCamelify(str) {
let returnStr = '';
for (const char of splitStr(str))
returnStr = editStrIfFalse(checkStrPosZero(splitStr(str), char), char);
return returnStr;
}
console.log(loopStrArrAndCamelify('hello_world'));
請注意,如果稍后重復第一個單詞,您的演算法將不起作用。strArr.indexOf(str)將回傳 的第一個匹配項的str索引,而不是迭代的當前索引,這將是0您處理第一個單詞的重復時。因此,例如,如果輸入是hello_world_hello,則結果將是helloWorldhello而不是helloWorldHello。
此外,如果一個單詞的第一個字母重復,你也會遇到同樣的問題——它將所有重復的字母都轉換為大寫。就這樣hello_wow變成了helloWoW。
如果你要迭代,你應該迭代索引,而不是值,然后你可以測驗 if index == 0。但大部分迭代都不需要。要將單詞轉換為駝峰式,只需執行以下操作:
new_word = word[0].toUpperCase() word.substring(1).toLowerCase();
當你迭代單詞時,使用for (let index = 1; index < words.length; index )只處理第一個單詞之后的單詞。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/530017.html
