我正在尝试使用 javascript 反转字符串。这是我的代码:
<!DOCTYPE html>
<html>
<body>
<p id = "test"></p>
<script>
var a = prompt("Enter anything to reverse", "Type Here");
var b;
var c;
var d = a.length;
for (i=d;i>=1;i--){
b = a.substr(i,1);
c = c + b;
};
document.getElementById("test").innerHTML = "The reverse is " + c;
</script>
</body>
</html>
现在输出是undefined
。请帮忙!
最佳答案
1) 在执行 var c;
时它是 undefined
,所以 c = c + b
正在执行 undefined
+ 字符
2) 数组的索引为 0,因此您应该从 length - 1
开始并在索引 0 结束。
这是工作版本:
var a = prompt("Enter anything to reverse", "Type Here");
var b;
var c = "";
var d = a.length;
for (i= d - 1;i >= 0;i--){
b = a.substr(i,1);
c = c + b;
};
document.getElementById("test").innerHTML = "The reverse is " + c;
<!DOCTYPE html>
<html>
<body>
<p id = "test"></p>
</body>
</html>
关于javascript - 为什么在我尝试反转字符串时输出未定义?- javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41592950/