简体   繁体   中英

Iteration of string in for loop doesn't work as expected

Being a beginner I am keen to sharpen my terrible Javascript skills. So I am tackling some Javascript challenges I found at rmion.com . I am stuck on #4 (I really do mean stuck, I've done my best on my own before bringing it to stackoverflow).

The instruction is: Write a function translate() that will translate a text into “rövarspråket”. That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".

Here is what I've come up with so far:

var vowel = 'a,e,i,o,u';
newString = '';
function vowelCheck(character) {
  for (var i = 0; i < character.length; i++) {
    if (character !== vowel[i]) {
      return newString + ((character[i]+character[i])+'o');
    } else {
      return newString + (character[i]+'o');
    }
  }
}
vowelCheck('abc');

I need the loop to run for every character abc which should return:

a,o,b,b,o,c,o

However, because the function returns a value with a string length equal to the function's given parameter .length it stops running the loop.

vowelCheck("abc");
// returns "aao"

Is it possible with the code I've written to make function run for each letter in vowelCheck("abc"); ?

I haven't looked at rmion 's given solution because I'm trying to see where I am going wrong. If it is not possible with what I've written, any hints would be great ^^ (I'm not looking for freebies)

The main issue is this line:

if (character !== vowel[i])

It's not really doing anything.

What you could do is use an array to hold the vowels:

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

and then check to see if the character is in that array:

// if vowels does NOT contain the character...
if (vowels.indexOf(character[i]) === -1)

Finally:

return newString + ((character[i]+character[i])+'o');

will not return the complete string, only the first part of the string, and I don't think it will generate the output you want.

newString += ((character[i] + 'o' + character[i]));

will keep adding the substrings to the output string which you can then return at the end of the function.

Here's a working example you can reference if you want to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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