1

我的 if 语句中的逻辑有问题。我试图让它检查字符串字符是否等于 a、e、i、o 或 u。然后如果是这样,将字符添加到短语字符串中。否则将“x”添加到短语字符串。

if 语句似乎忽略了我的 OR 逻辑并返回 true,无论它是不是元音。

function translate(string){
    var phrase = "";

    for(i=0; i<string.length; i++){
        if (string.charAt(i) === "a" || "e" || "i" || "o" || "u"){
           phrase += string.charAt(i);

       }else{

            console.log("x");

         }
    }
    console.log(phrase);
}


translate("this is fun");

任何帮助将不胜感激!谢谢你。

4

5 回答 5

5
if (string.charAt(i) === "a" || "e" || "i" || "o" || "u"){

这是不正确的。如果第一个条件失败(字符不是"a"),它将始终为,因为它会评估"e",这是(JavaScript 返回条件中表达式的最后评估部分)。

你可以用...

// Define them somewhere out of the loop.
var vowels = ["a", "e", "i", "o", "u"];

// Your new condition.
if (vowels.indexOf(string.charAt(i)) > -1) {

你也可以重写整个事情,比如......

var vowels = ["a", "e", "i", "o", "u"];
var phrase = string
              .split("")
              .filter(function(char) { return vowels.indexOf(char) > -1; })
              .join("");

js小提琴

于 2013-04-26T01:33:26.667 回答
2

您需要分别检查每个条件。例如:

if (string.charAt(i) === "a" || string.charAt(i) === "e" || ...);

要减少代码膨胀,您可以设置一个变量:

var char = string.charAt(i);

if (char === "a" || char === "e" || ...);

或者你可以使用这个indexOf技巧:

if (["a", "e", "i", "o", "u"].indexOf(string.charAt(i)) > -1);
于 2013-04-26T01:34:34.817 回答
1

像这样做。on 字符串比on Arrays.indexOf()更广泛可用。.indexOf()

if ("aeiou".indexOf(string.charAt(i)) > -1) {
于 2013-04-26T01:47:11.010 回答
1

Alex 的回答非常好,但与其使用indexOf和一个数组(注意Array.prototype.indexOf是 ES5,所以旧版浏览器不支持),您可以使用一个对象:

var vowels = {a:'a', e:'e', i:'i', o:'o', u:'u'};

if (vowels.hasOwnProperty(string.charAt(i).toLowerCase())) {
    phrase += string.charAt(i);
} else {
    ...
}

以上也不区分大小写,因此 A、E、I、O 和 U 也会添加到字符串中。如果您希望它区分大小写,请删除该.toLowerCase()部分。

编辑

亚历克斯让我再次思考。要按顺序返回仅包含元音的数组:

function getVowels(s) {
  return s.match(/[aeiou]/g);
}

要返回一个字符串,其中所有非元音(辅音)都被替换为“x”:

function replaceConsonants(s) {
  return s.replace(/[^aeiou]/g,'x');
}

要返回仅包含元音的字符串:

function replaceConsonants(s) {
  return s.replace(/[^aeiou]/g,'');
}

或者

function getVowels(s) {
  return s.match(/[aeiou]/g).join('');
}

等等

于 2013-04-26T02:04:19.923 回答
1

在您的代码中,您正在比较string.charAt(i)which"a" || "e" || "i" || "o" || "u"的计算结果为true.

你们男人要做的是:

string.charAt(i) === "a" || string.charAt(i) === "e" 
|| string.charAt(i) === "i" || string.charAt(i) === "o" || string.charAt(i) === "u"

在英语中我们说:if my string is equal to 'a' or 'e' or 'i' ..但在 javascript(和大多数其他语言)中,我们说:if my string is equal to 'a' or my string is equal to 'b' ..

于 2013-04-26T01:34:00.453 回答