2016-07-16 70 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");