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

11th Jul 2018, 8:25 PM
Sammy
Sammy - avatar
5 Answers
+ 3
change i = x.length; to i = x.length - 1;
11th Jul 2018, 9:09 PM
Ben Allen (Njinx)
Ben Allen (Njinx) - avatar
+ 2
Can you put this in the PlayGround?
11th Jul 2018, 8:59 PM
Ben Allen (Njinx)
Ben Allen (Njinx) - avatar
+ 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.
11th Jul 2018, 10:28 PM
James
James - avatar
+ 1
thanks Ben
11th Jul 2018, 9:25 PM
Sammy
Sammy - avatar
+ 1
ok
17th Jul 2018, 3:14 PM
Hendrik Macca
Hendrik Macca - avatar