【问题标题】:why will for loop not recognize || operator? [duplicate]为什么for循环不能识别||操作员? [复制]
【发布时间】:2014-06-02 21:29:02
【问题描述】:

我在没有老师的情况下做练习题,所以我上网寻求帮助。

我正在尝试解决这个问题:

编写一个函数 translate() 将文本翻译成“rövarspråket”。也就是说,将每个辅音加倍,并在其间放置一个“o”。例如, translate("this is fun") 应该返回字符串 "tothohisos isos fofunon"。

但是,当我尝试区分元音和辅音时,我遇到了一个问题。这就是我所拥有的:

function translate(text){
var newText;
if (!(text.charAt(0) ==  "a" || "e" || "i" || "o" || "u")){
    newText = text.charAt(0) + "o" + text.charAt(0);
    } else {
        newText = text.charAt(0);
    }
for (var i = 0; i<text.length; i++){
    if (!(text.charAt(i) ==  "a" || "e" || "i" || "o" || "u")){
        newText += text.charAt(i) + "o" + text.charAt(i);
    } else {
        newText += text.charAt(i);
    }
} 
console.log(newText);
}

translate("hello this is"); 

谁能解释为什么 ||运营商不工作?我认为这将解决我遇到的问题。

【问题讨论】:

    标签: javascript for-loop operator-keyword


    【解决方案1】:

    您误用了 OR 运算符;每个条件都需要完成。试试这个:

    if (!(text.charAt(0) == "a"
        || text.charAt(0) == "e"
        || text.charAt(0) == "i"
        || text.charAt(0) == "o" 
        || text.charAt(0) == "u") ){
    

    作为替代方案(因为这会很快变得笨拙),您可以将元音存储在单独的数组中,然后检查给定字符是否在数组中。

    var vowels = ["a", "e", "i", "o", "u"];
    if(vowels.indexOf(text.charAt(0).toLowerCase()) === -1) {
        // Vanna, I'd like to buy a vowel
    }
    else {
        // Consonant
    }
    

    【讨论】:

    • 或者你知道.. !"aeiou".split("").some(function(el){ return text[0] === el;})
    • 哇,谢谢@ChrisForrence!那是最简单的解决方法。我会在允许的时候检查它(大约 8 分钟后)。
    • 或者,你知道...!/[aeiou]/.test(text[0])
    • Ben,你是对的(只要你记得让它处理大小写)。但是,现在让我们从更基本的级别开始。但是@user2373912,请记住,有更有效的方法来做这样的事情,为了好玩,您应该尝试了解 如何 Ben 的第一种方法是如何工作的
    猜你喜欢
    • 1970-01-01
    • 2020-02-26
    • 2020-12-16
    • 2015-10-23
    • 2012-06-24
    • 1970-01-01
    • 2021-06-04
    • 2010-10-17
    • 1970-01-01
    相关资源
    最近更新 更多