我想制作一个代码;a“;变成“;b”"b”;变成“;c”;,等等
I want to make a code to turn "a" into "b", "b" into "c", and so on
我正在使用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);
相关文章:
- 铬:“;未捕获的语法错误:意外的标记:"
- 可以设置“;文件名"发生错误时显示的内联脚本标记的
- JS表单提交"无法使用Chrome数据保护程序加载此页面.尝试重新加载页面.调试信息:POST CISmtuK
- 检测电话窃听,即:<a href="电话:xxx">在UIWebview上
- 使用“+="操作人员
- //而不是在src=“”上使用http://"属性
- "未捕获的语法错误:意外的标记}"
- 可以<脚本类型=“;text/javascript”>window.location=“/"</
- "实例范围”;TypeScript类的getter/setter
- Javascript复选框函数:;缺少:在属性id之后"
- "“;变量未引用正确的对象
- "日期“;AJAX请求返回的类型值未定义
- 得到"TypeError:无法读取属性'filename'未定义的“;调用“npm start
- Soundcloud api"未捕获的类型错误:无法读取属性'uri'“未定义”;
- "工具提示"jQuery插件坏了
- "锻造;React中的表达式
- 图像可以从源<img src=""/>.TEXT可以在没有javascript的情况下从外部
- 如何提取“;href"最近列表项中的属性值
- CKEditor如何允许href="javascript:void(0)"在小部件中
- 我想制作一个代码;a“;变成“;b”"b”;变成“;c”;,等等