[英]I don't know how to fix my reverse array/string
so I need to be able to enter a string and have it reversed. 所以我需要能够输入一个字符串并将其取反。 I must have one library JS file and one regular JS file.
我必须有一个库JS文件和一个常规JS文件。 Here is my library JS file:
这是我的库JS文件:
function reverseString(string) {
var reversedString= "";
for(var i = string.length -; i >=; --i) {
reversedString = reversedString + string[i];
}
return reversedString;
}
and here is my regular one 这是我的常客
var stringEntered = prompt("Enter a string:")
var newString = reverseString(stringEntered);
document.write("the reverse of the string \" + stringEntered + \ " is \" + newString + ".")
I entered it the exact same way my professor showed us, and I when I try to run my HTML file (which is coded to call both these files), nothing happens. 我输入的内容与教授向我们展示的方式完全相同,当我尝试运行HTML文件(被编码为调用这两个文件)时,没有任何反应。 What am I missing?
我想念什么?
There're a lot of syntax issues. 有很多语法问题。 Here's a working code:
这是一个工作代码:
function reverseString(string) { var reversedString = ""; // This loop had a lot of basic syntax issues and also // "i" was starting from the length value, while a string // is a character array and array indexes start from 0 instead of 1 for (var i = string.length - 1; i >= 0; --i) { reversedString = reversedString + string[i]; } return reversedString; } var stringEntered = prompt("Enter a string:"); var newString = reverseString(stringEntered); // Here I found a mess of "/" characters // I've changed the horrible document.write with alert so you can check the result without opening the debugger... alert("the reverse of the string " + stringEntered + " is " + newString + ".")
Here is a concise method of reversing a string: 这是一种反转字符串的简洁方法:
function reverseString(string) { return string.split('').reverse().join(''); } var str = prompt("Enter a string", "a racecar dad"); alert(reverseString(str));
Turn it into an array, reverse the array, turn it back into a string. 将其转换为数组,反转数组,将其返回为字符串。
Edit : Sorry, didn't see @SidneyLiebrand's comment telling you to do the same. 编辑 :对不起,没有看到@SidneyLiebrand的注释告诉您要这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.