javascript 循环迭代太多

javascript loop iterating too much

尝试将字符串中的元音替换为行中的下一个元音 a->e、e->i、i->o、o->u 的有趣问题,不考虑 "u" .以数组而不是字符串开头。我的第二个循环(遍历元音数组元素)忽略了我的“j

var vowelChange = function(vowelArray, stringToChange) {
for (var i = 0; i<stringToChange.length; i++) {
    for (var j = 0; j<vowelArray.length; j++) {
      if (stringToChange[i]===vowelArray[j]) {
        var newCharacter = vowelArray[j+1]
          stringToChange[i] = newCharacter
          i++
      }
    }
}
return stringToChange
};

我正在使用 node-debug 在浏览器中设置断点,j 在从 0 重新开始之前循环到 5。我得到了正确的输出,但是 j 应该在 4 处停止...

编辑

谁能解释一下我是如何错误地使用 join 的,因为我无法让我的函数输出一个字符串而不仅仅是一个数组。

var vowelChange = function(vowelArray, stringToChange) {
for (var i = 0; i<stringToChange.length; i++) {
    for (var j = 0; j<vowelArray.length-1; j++) {
      if (stringToChange[i]===vowelArray[j]) {
          stringToChange[i] = vowelArray[j+1]
          break
      }
    }
  }
  stringToChange = stringToChange.join('')
  return stringToChange
};


var vowels = ['a','e','i','o','u']
var firstName = ['t', 'e', 's', 't']

vowelChange(vowels, firstName)
console.log(firstName)

假设 vowelArray 是从 0 开始索引的...

var vowelChange = function(vowelArray, stringToChange) {
    for (var i = 0; i<stringToChange.length; i++) {
        for (var j = 0; j<vowelArray.length - 1; j++) {
            if (stringToChange[i]===vowelArray[j]) {
                stringToChange[i] = vowelArray[j+1];
                break;
            }
        }
    }
    return stringToChange
};

In JavaScript, strings are immutable objects, which means that the characters within them may not be changed and that any operations on strings actually create new strings.

因此,如果您尝试更改字符串的任何索引,原始字符串不会更改

node
> str = "hello this is dummy string";
'hello this is dummy string'
> str[0] = "w";
'w'
> str
'hello this is dummy string'

所以,stringToChange[i] = vowelArray[j+1]; 行不通

可以拆分字符串然后加入

var vowelChange = function(vowelArray, stringToChange) {
    stringToChange = stringToChange.split('');
    for(var i=0; i<stringToChange.length;i++){
        for(var j=0;j<vowelArray.length-1;j++){
            if(stringToChange[i] == vowelArray[j]){
                stringToChange[i] = vowelArray[j+1];
                break;
            }
        }
    }
    stringToChange = stringToChange.join('');
    return stringToChange;
};

Example