挑战是什么:
使用JavaScript语言,让函数LetterChanges(str)获取传递的str参数,并使用以下算法对其进行修改。将字符串中的每个字母替换为字母表后面的字母(即c变为d,z变为a)。然后大写这个新字符串(a,e,i,o,u)中的每个元音,最后返回这个修改后的字符串。
我的解决方案:
function LetterChanges(str) {
var alphabet = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z];
var vowels = [a,e,i,o,u];
var stringToArray = str.split("");
for (i=0; i<=stringToArray.length; i++){ //goes through new array one-by-one
var originalLetter = stringToArray[i] // names each letter
var alphabetPosition = alphabet.indexOf(); // finds letter position in alphabet array
var newAlphabetPosition = alphabetPosition + 1; // adds one to that position
var newLetter = alphabet[newAlphabetPosition]; // changes the old letter to the new
newLetter = stringToArray[i]; // sends new letter to its position on new array
if (newLetter.isInArray(vowels){ // finds if new letter is a vowel
newLetter = newLetter.toUpperCase(); // if yes, turn into upper case
}
str = stringToArray.toStr() //turns array back to string, and names it str
}
return str;
}
我试图非常清楚我的想法,逐一添加步骤。请不要使用快速方法,因为我真的想要正确理解挑战背后的原因,而不是记住方法。
答案 0 :(得分:0)
代码不起作用......因为有一些错误:
function LetterChanges(str) {
for (var i = 0; i < str.length; i++) {
var newCharCode = str.charCodeAt(i) + 1; //Get Decimal Value for character at index "i", and increment by 1.
if (newCharCode == 123) { //Pesky 'z' becomes '{'. Lets change it to 'a' instead.
newCharCode = 97; // 'a' = 97.
}
if ([97,101,105,111,117].indexOf(newCharCode)!=-1) { //Is it a vowel? (97 = a, 101 = e, 105 = i, 111= o, 117 = u)
newCharCode-=32; //Make it capital. (65 = A, 69 = E, 73 = I, 79 = O, 85 = U)
}
console.log(newCharCode);
str = str.substr(0,i) + String.fromCharCode(newCharCode) + str.substr(i+1); //Convert it back to a character, and stick it back into the string.
console.log(str);
}
return str;
}
我标记了一些快速的东西...只是为了好玩。 (未经测试)它只使用2个变量,并做了一些老式的ascii技巧。
答案 1 :(得分:0)
我的CoderByte解决方案(https://github.com/ambatiramireddy/My-CoderByte-Solutions)
function LetterChanges(str) {
var vowels = 'aeiou', result = '', changedChar;
for (i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
if (c >= 97 && c < 122)
changedChar = String.fromCharCode(c + 1);
else if (c == 122)
changedChar = String.fromCharCode(97);
else
changedChar = str[i];
if (vowels.indexOf(changedChar) != -1)
changedChar = changedChar.toUpperCase();
result += changedChar;
}
return result;
}