簡體   English   中英

我不知道如何解決我的反向數組/字符串

[英]I don't know how to fix my reverse array/string

所以我需要能夠輸入一個字符串並將其取反。 我必須有一個庫JS文件和一個常規JS文件。 這是我的庫JS文件:

function reverseString(string) {
    var reversedString= "";
    for(var i = string.length -; i >=; --i) {
    reversedString = reversedString + string[i];
    }
    return reversedString;
}

這是我的常客

var stringEntered = prompt("Enter a string:")
var newString = reverseString(stringEntered);
document.write("the reverse of the string \" + stringEntered + \ " is \" + newString + ".")

我輸入的內容與教授向我們展示的方式完全相同,當我嘗試運行HTML文件(被編碼為調用這兩個文件)時,沒有任何反應。 我想念什么?

有很多語法問題。 這是一個工作代碼:

 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 + ".") 

這是一種反轉字符串的簡潔方法:

 function reverseString(string) { return string.split('').reverse().join(''); } var str = prompt("Enter a string", "a racecar dad"); alert(reverseString(str)); 

將其轉換為數組,反轉數組,將其返回為字符串。

編輯 :對不起,沒有看到@SidneyLiebrand的注釋告訴您要​​這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM