Reputation: 1
When I call this function, sending for example: abc as the parameter, the function returns: undefinedcba. I can't figure out why it's adding 'undefined' to my returned value. I'm probably overlooking something obvious but I can't spot it. Thank you.
function FirstReverse(str) {
var str_arr1 = new Array();
var ans = '';
for(i=0; i < str.length; i++) {
str_arr1.push(str.charAt(i));
}
for(j=str.length; j >= 0; j--) {
ans += str_arr1[j];
}
return ans;
}
Upvotes: 0
Views: 369
Reputation: 5922
Looks like you want to reverse a string, which you can do in this javascript one liner
function reverse(s){
return s.split("").reverse().join("");
}
The reason you are getting an undefined is because your j
starts with str.length
, whereas it should be str.length-1. str_arr1[str.length]
is out of bounds and therefore will be undefined.
Upvotes: 0
Reputation: 29025
Because when you pass 'abc' there are only 3 characters in it.
So arrray str_arr
have elements at index 0, 1 and 2.
But you are looping for str.length
i.e. for 3 times and str_arr[3]
is not defined.
You should do this,
function FirstReverse(str) {
var str_arr1 = new Array();
var ans = '';
for(i=0; i < str.length; i++) {
str_arr1.push(str.charAt(i));
}
for(j=str.length-1; j >= 0; j--) {
ans += str_arr1[j];
}
return ans;
}
Upvotes: 0
Reputation: 8114
The index of the string starts at 0, so string.length
is always one number bigger than index of the last character in the string.
In the second for loop, use
for(var j=str.length -1; j >= 0; j--) {
Upvotes: 1
Reputation: 11352
The error is in the second for
statement. See the solution:
function FirstReverse(str) {
var str_arr1 = new Array();
var ans = '';
for(i=0; i < str.length; i++) {
str_arr1.push(str.charAt(i));
}
for(j=str.length-1; j >= 0; j--) {
ans += str_arr1[j];
}
return ans;
}
Upvotes: 0
Reputation: 888203
Strings are 0-indexed. str[str.length]
does not exist.
j
needs to start at str.length - 1
.
Or, just return str_arr1.join();
Upvotes: 9