0

I want the array to switch places between the last one and the first. that the output will be 8-1 but when I try to do that the first index is undefined and the second is still 1

var arr1 = [1, 2, 3, 4, 5, 6, 7, 8];

for (var i = 0; i <= arr1.length / 2; i++) {
  var tmp = arr1[i];
  arr1[i] = arr1[arr1.length - i];
  arr1[arr1.length - i] = tmp;
};

console.log(arr1);

does anyone can help me to understand why?

adiga
  • 34,372
  • 9
  • 61
  • 83
  • 2
    `arr1.length-i` should be `arr1.length-i-1` – TKoL Feb 25 '19 at 12:43
  • 7
    You should know that there's a `reverse` function on the Array prototype as well – TKoL Feb 25 '19 at 12:45
  • Possible duplicate of [Javascript swap array elements](https://stackoverflow.com/questions/872310/javascript-swap-array-elements) – Lloyd Feb 25 '19 at 12:49

1 Answers1

3
for (var i =0; i<= arr1.length/2;i++){
  var tmp = arr1[i];
  arr1[i] = arr1 [arr1.length-i-1] ;
  arr1 [arr1.length-i-1] = tmp ;
};

We subtract 1 because when i is 0, arr1.length-i is the array length, which is off the end of the array already.

I don't think i<=arr1.length/2 is necessarily right either, 4 and 5 don't get swapped (or maybe they get swapped twice). I tried this and it worked: i<= arr1.length/2-1. Also this worked: i < arr1.length/2. Tested both of those with even and odd array length as well, seems fine. Second one probably makes more sense lol.

TKoL
  • 13,158
  • 3
  • 39
  • 73