Reputation: 11
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?
Upvotes: 0
Views: 46
Reputation: 13892
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.
Upvotes: 3