JavaScript Pig Latin元音逻辑错误,请求代码反馈

JavaScript Pig Latin vowel logic error, requesting code feedback

我正在做 Pig Latin 练习,但我不明白我的元音逻辑有什么问题导致 console.log 未定义?

function pigLatin(str){
    const vowel = ["a", "e", "i", "o", "u"];
    if(str.charAt(0) == vowel) {
        return str + "way";
    }
}

但是,如果我要测试不以元音开头的单词,我的代码运行良好。

function pigLatin(str){
        const vowel = ["a", "e", "i", "o", "u"];
        if(str.charAt(0) !== vowel) {
        var firstChar = str.slice(0, 1);
        return str.slice(1) + firstChar + "ay";
        } 
    }

为什么第一段代码设置不正确?我忽略或误解了什么?谢谢。

您在 if 块中使用的条件是错误的——您正在检查 str 的第一个字符是否等于 vowel 数组本身。这将始终是 false.

另外,第二个示例中使用的条件只是对第一个示例的否定,它的计算结果始终为 trueif 块将 运行 也用于以元音开头的字符串。

function pigLatin(str){
        const vowel = ["a", "e", "i", "o", "u"];
        if(str.charAt(0) !== vowel) {
        var firstChar = str.slice(0, 1);
        return str.slice(1) + firstChar + "ay";
        } 
    }
    
console.log(pigLatin('arnor'))

将您的代码更改为如下所示,以检查 str 的第一个字符是否是 vowels 数组 的成员:

function pigLatin(str){
    const vowel = ["a", "e", "i", "o", "u"];
    if(vowel.indexOf(str.charAt(0)) >= 0) {
        return str + "way";
    }
}

console.log(pigLatin('arnor'));
console.log(pigLatin('beorn'));

感谢 Yaakov Ainspan 和 Ramya Ramanthan 的澄清和在第二个区块中发现我的错误!

这是我经过大量研究和试验得出的结论。

function pigLatin(str){
    const vowel = ["a", "e", "i", "o", "u"];
    const consonant = "/[^aeiou]{2,}/"
    if(vowel.indexOf(str.charAt(0)) >= 0) {
        return str + "way";
    } else {
        for (var i = 0; i < str.length; i++){
            if(consonant.indexOf(str[i]) >= 0){
                var firstChar = str.slice(0, i);
                var multiCon = str.slice(i, str.length);
                return multiCon + firstChar + "ay";
            }
        }
    }
}

起初我 运行 遇到与 if 字符串中 consonant 变量中的第二个块相同的问题。原来我犯了同样的错误——将 str 检查到数组。在我将 const consonant 包装在字符串而不是数组方括号中后问题消失了。

如果我的代码仍然存在我没有预见到的问题,请务必告诉我。 :)

注意:我知道关于以辅音开头但听起来像元音的单词的其他 pig latin 规则(例如,"honest" 在我的代码中是 onesthay 而不是 honestway)。我忽略了这条规则。