javascript - Why does my code always end with undefined? -
i wrote javascript code, ends **undefined**mycode? have done wrong/ how can prevent in future. running code through chrome javascript console.
here code
//reverse string //-------------------------// //input string var string = prompt("please enter string"); //console.log(string); //find length of string var stringlength = string.length; //console.log(stringlength); //creating empty string outputting answer var reversedstring = ""; //start length of string , work backwards, inputting letter 1 @ time. (var = stringlength; >= 0; i--){ reversedstring += string[i]; //console.log(string[i]); } //outputting reversed string; alert(reversedstring);
thanks answers in advance
change loop
for (var = stringlength; >= 0; i--){
to
for (var = stringlength-1; >= 0; i--){
the problem is, array indices in javascript 0 based.
lets string entered in prompt "abc", length of string 3. in loop, access string[3]
undefined. hence error.
here fiddle demonstrating updated code:
Comments
Post a Comment