簡體   English   中英

這個簡單的代碼可以幫助我嗎?

[英]Can anyone help me with this simple code?

function isVowel(char){

    if(typeof char == 'string' && char.length > 1){
        console.log('not a char');
        return 'not a char';
    } else {
        if (char.toLowerCase() === ('a'||'e'||'i'||'o'||'u')){
            console.log(char, true);
            return true;
        } else {
            console.log(char, false);
            return false;
        }
    }
}

document.writeln(isVowel('a'));
document.writeln(isVowel('e'));
document.writeln(isVowel('l'));

結果是:true,false,false;

它應該是:真實,真實,虛假;

任何人都可以幫助我為什么會這樣嗎?

我只是在學習JavaScript ......

另外,有沒有辦法重構這段代碼? 我不想為每一個新情況重復自己..

你需要分開|| 是這樣的:

char.toLowerCase() === 'a'
|| char.toLowerCase() === 'e'
|| char.toLowerCase() === 'i'
|| char.toLowerCase() === 'o'
|| char.toLowerCase() === 'u'

而不是像這樣:

char.toLowerCase() === ('a'||'e'||'i'||'o'||'u')

這是以上的jsFiddle:

('a'||'e'||'i'||'o'||'u')等於"a"

要確認以上內容,只需使用控制台進行嘗試,或者:

console.log(('a'||'e'||'i'||'o'||'u'));

我的建議:

' aeiou'.indexOf(char) > 0

完整版:

function isVowel(char){

    if(typeof char == 'string' && char.length > 1){
        console.log('not a char');
        return 'not a char';
    } else {
        if (' aeiou'.indexOf(char) > 0){
            console.log(char, true);
            return true;
        } else {
            console.log(char, false);
            return false;
        }
    }
}

document.writeln(isVowel('a'));
document.writeln(isVowel('e'));
document.writeln(isVowel('l'));

重構版本:

function isVowel(char)
{
    return ((typeof char == 'string') && (char.length == 1) && ('aeiou'.indexOf(char.toLowerCase()) != -1));
}
    if (/[aeiou]/.test(char.toLowerCase())){
      // ...
    } else {
      // ...
    }

問題出在這里

if (char.toLowerCase() === ('a'||'e'||'i'||'o'||'u'))

平等運營商不“分配”,你必須獨立測試每種可能性的輸入。 一個簡潔的解決方案可能是

if ("aeiou".indexOf(char.toLowerCase()) + 1) {
    console.log(char, true);
    return true;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM