function reverseArray(array) {
var reversed_array = [];
for(var i = 0; i < array.length; i++) {
reversed_array.unshift(array[i]);
}
return reversed_array;
}
function reverseArrayInPlace(array) {
console.log(array); //[1,2,3,4,5]
array = reverseArray(array);
console.log(arguments); //{0: [5, 4, 3, 2, 1]} this is good.
console.log(array); // [5, 4, 3, 2, 1] this is also good.
return array; //should return [5, 4, 3, 2, 1]
}
console.log(reverseArray(["A", "B", "C"])); //["C", "B", "A"]
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue); // [1, 2, 3, 4, 5] *wrong*
here is the problem I want to override the variable (arrayValue) with the return value of reverseArrayInPlace() just like array.reverse() does.
and here is a solution for the problem
function reverseArrayInPlace(array) {
var half = Math.floor(array.length / 2);
for(var i = 0; i < half; i++) {
var current = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = current;
}
console.log(array); // [5, 4, 3, 2, 1] this is good.
return array; //should return [5, 4, 3, 2, 1]
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue); // [5, 4, 3, 2, 1] *it works!*
I don't understand why this solution works in replacing (arrayValue) with the new value, if both reverseArrayInPlace() functions have a return statement with the same value.
Can someone please explain I'm fairly new to programming, thanks!