2016-07-16 72 views
1

我正在做Free Code Camp的篝火之一,我已經接近尾聲,但最後一點我找不出來!缺少字母功能 - 爲什麼它返回undefined?

函數應該帶一個字符串並返回丟失的字母(基於字母表a-z)。它工作正常,除了當缺少的字母是'我',它返回未定義。

我放了一個額外的if語句來檢查當缺少的字母是'i'時,它符合其他if語句的標準(因此應該執行這些代碼行)並匹配,所以我已經不知道爲什麼它會返回undefined。

function fearNotLetter(str) { 
 
    missingLetter = ''; 
 
    charCode = 0; 
 
    
 
    for (i = 0; i < str.length -1 ; i++) { 
 
    charCode = str.charCodeAt(i); 
 

 
    if (str.charCodeAt(i + 1)-charCode == 2) {    
 
     missingLetter = str.charCodeAt(i)+1; 
 
     missingLetter = String.fromCharCode(missingLetter); 
 
    } else { 
 
     missingLetter = undefined; 
 
    } 
 
    } 
 
    
 
    console.log(missingLetter); 
 
    return missingLetter; 
 
} 
 
    
 
fearNotLetter("abcdefghjklmno");

真的很感謝所有幫助任何人都可以給。

在此先感謝。

+0

感謝您的答案傢伙 - 這是偉大的!對於我的學習,關於爲什麼只有某些字符串返回undefined而不是其他字符的想法? – StevenWalker

回答

1

因爲您將每個回合中的值都設置爲undefined,即使您之前在循環中找到了一個。

我建議在使用前聲明所有變量與var關鍵字並初始化missingLetterundefined

然後你可以break循環,如果找到丟失的字母。

function fearNotLetter(str) { 
 
    var missingLetter = undefined, 
 
     charCode, 
 
     i; 
 

 
    for (i = 0; i < str.length - 1 ; i++) { 
 
     charCode = str.charCodeAt(i); 
 
     if (str.charCodeAt(i + 1) - charCode == 2) { 
 
      missingLetter = String.fromCharCode(charCode + 1); 
 
      break; 
 
     } 
 
    } 
 
    return missingLetter; 
 
} 
 

 
console.log(fearNotLetter("abcdefghjklmno"));

+1

謝謝,這太棒了!一旦完成,我絕不會破壞代碼! – StevenWalker

+0

將變量初始化爲未定義沒有多大意義。另外,只是在找到它時返回值而不是打破循環會更簡單 - 那麼您甚至不需要變量。 – JJJ

+0

@Juhana,可以退出循環並且返回函數的權利,但是op有一個變量,它只是顯示如何處理默認值。 –

1

試試這個,你缺少突破循環一旦你丟失的信件,並在下一個迭代丟失盤符設置爲undefined

function fearNotLetter(str) { 
 
    missingLetter = ''; 
 
    charCode = 0; 
 

 

 
    for (i = 0; i < str.length -1 ; i++) 
 
    { 
 

 
    charCode = str.charCodeAt(i); 
 
    
 
    if (str.charCodeAt(i + 1)-charCode == 2) { 
 
    
 
     missingLetter = str.charCodeAt(i)+1; 
 
     missingLetter = String.fromCharCode(missingLetter); 
 
     break; 
 
    } 
 
    else 
 
    { 
 
     missingLetter = undefined; 
 
    } 
 
    } 
 
    console.log(missingLetter); 
 
    return missingLetter; 
 
} 
 
fearNotLetter("abcdefghjklmno");