javascript - while 循环无法正常工作

标签 javascript while-loop

我正在为 freecodecamp.com 上的一个练习编写代码,名为 Pig Latin问题。对于 while 循环,当条件错误时,它应该停止执行其中的代码。对于我的情况,当 while 循环发现在迭代期间在 Charas 数组中看到元音时,它必须停止执行其中的代码。我认为我的代码在我看来是正确的,但是 while 循环在看到元音时不会停止执行,而是会迭代 Charas 数组中的每个元素。

这是我的代码

function translatePigLatin(str) {
  var vowels = ['a','e','i','o','u'];
  var f="";
  var charas = str.split("");
  if(vowels.indexOf(charas[0])!==-1) {
      // vowel
    charas.push("w");
    charas.push("a");
    charas.push("y");
    f = charas.join("");
  } else {
    //if first letter  is a consonant or cluster of consonants
    var i = 0;
    while(vowels.indexOf(charas[i]) ===-1) {
     charas.push(charas[i]);
     charas.splice(i,1);
     i = i+1;
     }    
   charas.push('a');
   charas.push('y');
   f  = charas.join("");   
  }
  return f;
}

translatePigLatin("california");

最佳答案

它可以作为工作原因

 charas.push(charas[i]);
 charas.splice(i,1);
 i = i+1;

第一次迭代后,它在开头移动“a”字母,因为结果 i == 1(在第二次迭代中)charas[i] 引用辅音“l”。

关于javascript - while 循环无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42159262/

相关文章:

c - fscanf while-loop 从不运行

javascript - 如何在 Titanium 中插入垂直滚动条

javascript - 在我的猜数游戏中遇到 while 循环问题

java - 如何按数组中字符串的长度对 ArrayList 进行排序

javascript - 反向数组不包含每个元素

java - Thread.sleep() 在 while 循环中

ios - 基本 while 循环中索引超出范围

javascript - 图片上传不会失败

javascript - Onsubmit window.location 不工作

javascript - 如何在新的 div 中追加 li