简体   繁体   English

经典的元音练习。 我不知道为什么我的for循环无法正常工作

[英]classic vowel exercise. I can't figure out why my for loop isn't working

The exercise problem- Write a function translate() that will translate a text into "rövarspråket". 练习题-编写一个函数translate(),将文本转换为“rövarspråket”。 That is, double every consonant and place an occurrence of "o" in between. 也就是说,将每个辅音加倍,并在它们之间放置一个“ o”。 For example, translate("this is fun") should return the string "tothohisos isos fofunon". 例如,translate(“ this is fun”)应该返回字符串“ tothohisos isos fofunon”。

I don't understand why my code doesn't work. 我不明白为什么我的代码无法正常工作。

var word = prompt("Enter a word");

var vowels = ["a", "e", "i" ,"o", "u"];
var output;

for (var i=0; i < word.length; i++) {
    if (word.charAt(i) != "a" || "e" || "i" || "o" || "u" ) {
        output = word.charAt(i) + "o" + word.charAt(i);    
    } else {
        output = word.charAt(i);   
    }
    document.getElementById("paragraph").innerHTML = output;
}

try this: 尝试这个:

var word = prompt("Enter a word");

var vowels = ["a", "e", "i" ,"o", "u"];
var output;

for (var i=0; i < word.length; i++) {
 if (vowels.indexOf(word.charAt(i))==-1 ) {
     output += word.charAt(i) + "o" + word.charAt(i);    
 }
    else{
     output += word.charAt(i);   
    }
    document.getElementById("paragraph").innerHTML = output;
}

Notice that i replaced the word.charAt(i) with vowels.indexOf By using indexOf you can determin if something exists in an array by the returned value.indexof returns -1 if an element doesnot exist or the index of the element inside the array 请注意,我用vowels.indexOf替换了word.charAt(i),通过使用indexOf可以确定数组中是否存在返回值。如果元素不存在或数组中元素的索引,则indexof返回-1

This code 这段代码

if (word.charAt(i) != "a" || "e" || "i" || "o" || "u" ) {...}

means 手段

If [ (word.charAt(i) !="a") or "e" or "a" ... ] 如果[ (word.charAt(i) !="a")"e""a" ...]

And "e" evaluates as true when cast as boolean. 当将e转换为布尔值时,“ e”的评估结果为true。

The correct code to do what you're trying to do would be 做您想做的正确代码是

if (word.charAt(i) != "a") && (word.charAt(i) != "e")  && (word.charAt(i) != "i")  && (word.charAt(i) != "o")  && (word.charAt(i) != "u") ) {...}

In addition, change both the output = commands to output+= 此外,将两个output =命令都更改为output+=

This can be achieved in one line with regex : 这可以用regex 一行完成:

yourString.replace(/([bcdfghjklmnpqrstvwxz])/g, '$1o$1'); // Add the accepted characters here

In your example : 在您的示例中:

"this is fun".replace(/([bcdfghjklmnpqrstvwxz])/g, '$1o$1')

Outputs 产出

"tothohisos isos fofunon"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM