+ 2
I've just started learing JavaScript a few days ago and I've got a bug in my code, need help finding where it went wrong.
<!DOCTYPE html> <html> <head> <title>test </title> <script type="text/javascript"> function myfunction() { var x = document.getElementById('test').value; i=x.length; do { document.write(x[i]); i--; } while(i>=0); } </script> </head> <body> <p>enter a string:</p> <input id="test" type="text"/> <input type="submit" value="reverse" onclick="myfunction()"/> </body> </html> it's suppose to reverse the users input. but it keeps displaying "undefined" along with the reversed string.
5 Réponses
+ 3
change
i = x.length;
to
i = x.length - 1;
+ 2
Can you put this in the PlayGround?
+ 2
To explain Ben's answer, keys (which you write in square brackets) always begin at 0, so that last key is 1 less than the length.
["Hello", "World", "test"]
0 1 2
However, your input appears to be a string, not an array with keys. Therefore, you should use i.charAt(x) to single out characters, or you can split the string into an array using i.split(""); for single characters, or i.split(" "); for single words.
Lastly, it doesn't often matter, but JavaScript works best when the tags are at the very end of the body.
+ 1
thanks Ben
+ 1
ok