简体   繁体   中英

Why this reverse function isn't working?

Why isn't this working? ps. I don't want to use any other variable to make it work, and i don't want to use built in functions, just asking why THIS is not working?

function reverse(arr){
  for(var i =0; i< arr.length; i++){
    arr.push(arr[arr.length-i]);
  }
  return arr;
}

There are a lot of flaws in your code.

  • When you start pushing arr.push(arr[arr.length-i]); the array length increases, thereby, you won't get a consistency in the data.
  • This goes inside an infinite loop, as every time, the arr is ahead of its length.

It is better to use another variable and reverse, or you can use the built-in reverse() function. There's nothing wrong in having another variable and add temporary contents in it.

Solutions:

Using a temporary array:

function reverse(arr) {
    var final = [];
    for (var i = arr.length - 1; i >= 0; i--) {
        final.push(arr[i]);
    }
    return final;
}

Using built-in function ( Array.prototype.reverse() ) :

function reverse(arr) {
    return arr.reverse();
}

Using few temporary variables:

 a = [5,4,3,2,1]; function reverse(arr) { var i = 0, j = arr.length - 1; for (i = 0; i < j; i++, j--) { var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } return arr; } console.log(reverse(a)); 

I don't want to use any other variable to make it work, and i don't want to use built in functions

You cannot.


Use temporary array for result

function reverse(arr) {
    var res = []
    for (var i = arr.length - 1; i > -1; i--) {
        res.push(arr[i]);
    }
    return res;
}

You're going to run out of memory. What you're doing is adding what was initially the last element of that array infinitely to the end of your array. Every time that you call arr.push(...) you increase arr.length by one. Your for loop will never be able to finish because i will never be less than arr.length

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM