gpt4 book ai didi

javascript - Coderbyte 字母更改挑战 - else 语句错误

转载 作者:行者123 更新时间:2023-11-28 06:04:49 25 4
gpt4 key购买 nike

我正在 coderbyte 中进行字母更改挑战,但我很困惑为什么我的代码不起作用。

Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm.

Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a).

Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.

在最后一个 else 语句中,我想将不是字母的任何字符添加到“newWord”中。 When i pass the word "hello 3"I should be getting "ifmmp 3"instead I get "hhhhhhhihhhhhhhhhhhhhhhhhhheeeefeeeeeeeeeeeeeeeeeeeeeelllllllllllmllllllllllllllllllllllllllmllllllllllllllloooooooooooooopoooooooooooo 333333333333333333333333333undefined....."If i take that else statement out, I just get "ifmmp"without the 3. Im having trouble理解 else 语句为何/如何搞乱它,我该如何解决这个问题?我是编码新手,因此任何帮助都会很棒。

    function LetterChanges(str) { 
var newWord = "";
var alphabet = "abcdefghijklmnopqrstuvwxyz";
for(var i = 0; i <= str.length; i++){
if( str[i] === "z"){
newWord += alphabet.charAt(0);
} else if(str[i] === " "){
newWord +=" ";
}

for (var j = 0; j <= alphabet.length; j++){
if(str[i] == alphabet.charAt(j)){
newWord += alphabet.charAt(j+1);
}
// this one -------------------> else {
newWord = newWord + str[i];
}
}

}
return newWord;
}

最佳答案

试试这个:

function LetterChanges(str) { 
var newWord = "";
var alphabet = "abcdefghijklmnopqrstuvwxyz";
for(var i = 0; i < str.length; i++){

for (var j = 0; j < alphabet.length; j++){

if(str[i] === alphabet.charAt(j)){
if( str[i] === "z"){
newWord += alphabet.charAt(0);
}
else {
newWord += alphabet.charAt(j+1);
}
}
else if (alphabet.indexOf(str[i]) === -1){
newWord += str[i];
break;
}
}
}
return newWord;
}

以下是更有效的解决方案

function LetterChanges(str) { 
var newWord = "";
var alphabet = "abcdefghijklmnopqrstuvwxyz";
for(var i = 0; i < str.length; i++){
// if it's a 'z' do not loop through alphabet string and jump straight to the next character.
if( str[i] === "z"){
newWord += alphabet.charAt(0);
continue;
}
for (var j = 0; j < alphabet.length; j++){
// if they match perform replacement
if(str[i] === alphabet.charAt(j)){
newWord += alphabet.charAt(j+1);
break;
}
// if the current char is not contained on the alphabet string (spaces, numbers and so on...) ---> copy it as it is
else if (alphabet.indexOf(str[i]) === -1){
newWord += str[i];
break;
}
// if the current char is contained in the alphabet string but does not match ---> do nothing
}
}
return newWord;
}

关于javascript - Coderbyte 字母更改挑战 - else 语句错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36975703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com