我想制作一个代码;a“;变成“;b”"b”;变成“;c”;,等等

I want to make a code to turn "a" into "b", "b" into "c", and so on

本文关键字:变成 quot 等等 代码 一个      更新时间:2024-03-19

我正在使用JavaScript,到目前为止,我的代码如下所示:

var myText = prompt("Type your sentence.");
var newText = [];
for (var i = 0; i < myText.length; i++) {
     if (i = 'a') {
         newText = myText.replace(/a/g, "b");
    }
    else if (i = 'b') {
        newText = myText.replace(/b/g, "c");
    }
}
console.log(newText);

如果我输入"aba",它会返回"bbb",为什么?我能换什么?

var myText = 'aba';
var newText = "";
for (var i = 0; i < myText.length; i++) {
 if (myText[i] === 'a') {
     newText += "b";
}
else if (myText[i] === 'b') {
    newText += "c";
}
}
console.log(newText);

您使用的是=运算符,它将值分配给i,即使在条件语句中也是如此。它需要是==,甚至更好的===,因为它们是比较运算符。此外,您不想比较i,您想比较myText[i]处的字符。

首先,使用比较的语法是错误的。要使用的运算符为==或===。其次,您将循环变量与"a"或"b"进行比较,这在逻辑上是错误的,因为应该比较索引处的字符,而不是循环变量。满足您需求的代码片段:

var myText = "someinputstring";
var newText = "";
for (var i = 0; i < myText.length; i++) {
    if (myText[i] >= 'a' && myText[i] <= 'z') {            
        var n = myText.charCodeAt(i) + 1;
        if(n == 123) { n = 97; } // When character is 'z' it should be
                                 // replaced by 'a'
        newText = newText + String.fromCharCode(n);
    }
    else { // for anything other than 'a' to 'z'
        newText = newText + myText[i];
    }
}
console.log(newText);

并且存在逻辑故障:我是一个数字,这个数字不能是字符串。。。而是尝试使用

    var myText = prompt("Type your sentence.");
    var newText = "";
    for (var i = 0; i < myText.length; i++) {
        if(myText.substring(i,i+1) == "a"){
            newText +=  myText.replace(/a/g, "b");
        }
        else if(myText.substring(i,i+1) == "a"){
           newText += myText.replace(/b/g, "c");
        }
    }
    console.log(newText);

或更好地使用开关:

    var myText = prompt("Type your sentence.");
    var newText = "";
        for (var i = 0; i < myText.length; i++) {
            switch(myText[i]){
                case "a":
                newText += "b";
                break;
                case "b":
                newText += "c";
                break;
            }
        }
console.log(newText);