function reverseArrayInPlace(array) { var arrayTemp = array; var arrayResult = []; var arrayLength = array.length for (var i = 0; i <= arrayLength - 1; i++) { arrayResult.push(arrayTemp.pop()) } array = arrayResult; return array; } var arrayValue = [1, 2, 3]; reverseArrayInPlace(arrayValue) console.log(arrayValue)
In fact, your code works and works correctly. To verify this, let's output the value returned by the function instead of outputting the value of the source array:
function reverseArrayInPlace(array) { var arrayTemp = array; var arrayResult = []; var arrayLength = array.length for (var i = 0; i <= arrayLength - 1; i++) { arrayResult.push(arrayTemp.pop()) } array = arrayResult; return array; } var arrayValue = [1, 2, 3]; let res = reverseArrayInPlace(arrayValue); console.log(res); // [3, 2, 1] => работает!
The problem is that inside the function, you override the variable array . This variable initially points to the source array arrayValue , which you are trying to change "in place". You can verify this by adding console.log(array === arrayValue); which will print true .
This is because the arrays are transmitted "by reference", and not by copying. Therefore, you can freely change the values of the elements of the variable array , thereby changing the values of the same elements of the variable arrayValue outside of this function.
However, here is this line:
array = arrayResult;
You simply override the value of the variable array . Therefore, this variable no longer points to the same array that was originally ( arrayValue ). That is the problem.
And an empty array is displayed because you "cut out" all the elements from the original array with this construction:
arrayTemp.pop()
At the same time arrayTemp === array === arrayValue .
What to do?
First of all, do not override the value of the variable array . Second, do not cut elements from the original array. Thirdly, since it is impossible to override a variable referring to the original array for an on-site change, it is necessary:
- Create a copy of the original array (just assign it to a new variable, as you can see, cannot)
- Work with a copy (only if you want to leave the algorithm with
pop and push , but in general it is completely optional) - Alternately redefine the elements of the original array with the elements from the processed copy.
- Do not return anything from the function (although this is optional and will not break anything; it is just accepted).
The working algorithm is described in its answer @Igor, you can see there.
array = arrayResult;you change the local variable (the formal parameter of the function), but not the original array. - smellyshovel