在這段代碼中,我想回傳一串連續字母中缺少的字母,如果所有字母都存在,我想回傳未定義的。但是,它回傳定義的而不是回傳“{”,我在網上的任何地方都找不到類似的案例。
function fearNotLetter(str) {
for (let i = 0; i < str.length; i ) {
if (str.charCodeAt(i) !== str.charCodeAt(i 1) - 1) {
return String.fromCharCode(str.charCodeAt(i) 1)
}
}
return undefined
}
console.log(fearNotLetter("abcdefghijklmnopqrstuvwxyz"))
uj5u.com熱心網友回復:
您的代碼將每個字母與字串中緊隨其后的字母進行比較
你不能測驗最后一個字母,因為它后面什么都沒有
只需更改回圈,使其僅迭代到倒數第二個字母
function fearNotLetter(str) {
for (let i = 0; i < str.length - 1; i ) {
if (str.charCodeAt(i) !== str.charCodeAt(i 1) - 1) {
return String.fromCharCode(str.charCodeAt(i) 1)
}
}
return undefined
}
console.log(fearNotLetter("abcdefghijklmnopqrstuvwxyz"))
uj5u.com熱心網友回復:
在您回傳的 for 回圈中的示例中
String.fromCharCode(str.charCodeAt(i) 1)
在此回傳值中,當字符為 z 時,'z' 的 ascii 值為 122,而您回傳的 122 1 為 '{' 的 asci 值
這就是為什么你在你的例子中得到'{'
您可以通過從函式中傳遞的字串中洗掉“z”來進行測驗
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/437659.html
標籤:javascript for循环 不明确的
