I recently started learning Javascript from Eloquent Javascript and got up until the way of data structures.
There is one Coding Exercise as Follows
write two functions, reverseArray and reverseArrayInPlace. The first, reverseArray, takes an array as argument and produces a new array that has the same elements in the inverse order. The second, reverseArrayInPlace, does what the reverse method does: it modifies the array given as argument in order to reverse its elements. Neither may use the standard reverse method.
Here is My Code
/*
* Create a Function reverseArray which returns a new array with the reversed array
* Create another Function reverseArrayInPlace() which modifies the ORiginal Array .
*/
function reverseArray(array) {
var reversed = [];
for (var i = 0; i < array.length; ++i) {
reversed[i] = array[array.length - (i + 1)];
}
return reversed;
}
function reverseArrayInPlace(array) {
var temp = 0;
for (var i = 0; i < array.length; ++i) {
temp = array[i];
array[i] = array[array.length - (i + 1)];
array[array.length - (i + 1)] = temp;
}
}
// Test Case
var ar = [10, 9, 8, 7, 6];
console.log(reverseArray(ar));
// Reverse the Array
reverseArrayInPlace(ar);
console.log(ar);
The reverseArray() Function does it's job well , returning the reversed array , but the reverseArrayInPlace() is not working.
What did I do wrong ?