I need help with understanding how this code works. task: Without using functions, you must reverse all items in a list. That is, redo it back and forth.
Example: Input: [-89,71,11,0,4,6] Output: [6,4,0,11,71,-89]
I found this example, but I need to explain how it works and be able to explain all aspects of the code:
let arr = [1, 2, 3, 4, 5, 6, 7];
let n = arr.length-1;
for(let i=0; i<=n/2; i++) {
let temp = arr[i];
arr[i] = arr[n-i];
arr[n-i] = temp;
}
console.log(arr);
You can use much simpler like:
const arr = [1, 2, 3, 4, 5]
const reversedArr = []
for (let i = arr.length - 1; i >= 0; i--) {
reversedArr.push(arr[i])
}
console.log(reversedArr)
Explanation is just, iterating over each item in the original array, but starting from the last item (arr.length = 5 here) and push each of them to a new array.
The code is just doing a reverse function.
The let temp = arr[i];arr[i] = arr[n-i];arr[n-i] = temp; is trying to switch the sequence between the i item and the i item from the last element,.
In your code, n is the last element.
Example, i =0, temp will equal to be the first element in arr which is 1, and arr[n-i] will be the last i element (the last element) which is 7.
Then, the code set arr[i] (first element in arr) to the last element value arr[n-i] which is 7.
Finally, the code assign the value of the arr[n-1] (last element in arr) to temp which is 1 and the first element in arr .
So you successfully reverse the first and last element and the loop keep doing the same thing when i=1,2......
let arr = [1, 2, 3, 4, 5, 6, 7];
let n = arr.length-1;
for(let i=0; i<=n/2; i++) {
let temp = arr[i];
arr[i] = arr[n-i];
arr[n-i] = temp;
}
console.log(arr);