JavaScript:字符串没有像我预期的那样连接

JavaScript: String isn't concating like I expect

输入:"the quick brown fox"

预期结果:"ethay ickquay ownbray oxfay"
实际结果:"etayh ickquay ownbray oxfay"

出于某种原因,只有第一个单词出现了问题。

代码

if (str.match(/[ ]/)) {

        str = str.split(" "); 
        for (let i = 0; i < str.length; i++) {
            for (let j = 0; j < str.length; j++) {
                if (str[j].match(/^[q][u]/)) str[j] = str[j]
                    .substring(2) + str[j].slice(0, 2);
                if (str[j].match(/^[^aeiou]/)) {
                    str[j] = str[j].substring(1) + str[j].slice(0, 1);
                }
            }

            str[i] = str[i] + 'ay';
        }

        str = str.join(" ");

    }

这是因为您循环了两次,但只添加了一次 ay。因为 the 以两个辅音开头,所以 h 在第二次迭代时被推到末尾。

str = "the extra quick brown fox"
if (str.match(/[ ]/)) {
    str = str.split(" "); 
    for (let i = 0; i < str.length; i++) {
        for (let j = 0; j < str.length; j++) {
            if (str[j].match(/^[q][u]/)) str[j] = str[j]
                .substring(2) + str[j].slice(0, 2);
            if (str[j].match(/^[^aeiou]/)) {
                str[j] = str[j].substring(1) + str[j].substring(0,1);
            }
        }
        console.log(str[i])

        str[i] = str[i] + 'ay';
        console.log(str)
    }
    str = str.join(" ");

}
VM383:12 het
// Notice it is correct with the first pass.
VM383:15 (5) ["hetay", "extra", "ickqu", "rownb", "oxf"]
VM383:12 extra
// but it is incorrect after the second.
VM383:15 (5) ["etayh", "extraay", "ickqu", "ownbr", "oxf"]

您没有抓住 substring/slice 块中的所有辅音。更改您的正则表达式以包含所有辅音,然后使用该结果的长度来正确分割字符串。

str = "the quick brown fox".split(" "); 
for (let i = 0; i < str.length; i++) {
    for (let j = 0; j < str.length; j++) {
        if (str[j].match(/^qu/)) str[j] = str[j]
            .substring(2) + str[j].slice(0, 2);
        if (match = str[j].match(/^[^aeiou]+/)) {
            let charCount = match.toString().length;
            str[j] = str[j].substring(charCount) + str[j].slice(0, charCount);
        }
    }

    str[i] = str[i] + 'ay';
}

str = str.join(" ");

console.log(str);