Quick JavScript question. In the following pieces of code I'm reversing the array arr that's being passed to the function reverseArray.
In the first piece of code, it looks like that the local variable arr keeps changing even though inside the loop I am operating on the variable newArr which hold the initial value of arr. Hence the loop fails when arr.length reaches the values 3.
function reverseArray (arr) {
var newArr = [];
var inArr = arr;
console.log(inArr);
for (i = 0; i < arr.length; i++) {
newArr[i] = inArr.pop(i);
}
return newArr;
}
reverseArray(["A", "B", "C", "D", "E", "F"]);
// OUTPUT: ["F", "D", "E"]
On the other hand, if I store arr.length on local variable numArr, then it works perfectly and reverses the array.
function reverseArray (arr) {
var numArr = arr.length;
var newArr = [];
for (i = 0; i < numArr; i++) {
let inArr = arr;
newArr[i] = inArr.pop(i);
}
return newArr;
}
reverseArray(["A", "B", "C", "D", "E", "F"]);
// OUTPUT: ["F", "E", "D", "C", "B", "A"]
What am I missing?
pop()doesn’t take any arguments.