0

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; 
}

5 Answers 5

9

Strings are 0-indexed. str[str.length] does not exist.

j needs to start at str.length - 1.

Or, just return str_arr1.join();

Sign up to request clarification or add additional context in comments.

1 Comment

Or he could just rewrite his function to: function FirstReverse(str) { return str.split("").reverse().join(""); }
1

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--) {

Comments

0

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;
}

Comments

0

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;  
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.