The problem here is that you have nested for
loops, you take value from index of the outside loop and replace entire array with that value with inner loop, then continue to the next index of the ouside loop, so at the end you end up with the value from the last index of the outside loop.
What you need is one loop, and push()
value into new array:
const arr = [1, 2, 3, 4, 5, 6, 7];
function rev(arr) {
var value;
var nArr = [];
for (let i = arr.length - 1; i >= 0; i--) {
value = arr[i];
nArr.push(value);
}
console.log(nArr);
}
rev(arr);
Note, this is very inefficient method to achieve that, the answer from @dippas would be a better choice if you need the result, not the journey ;)
[EDIT]
To better understand what's happening in your original code use console.log()
:
const arr = [1, 2, 3, 4, 5, 6, 7];
function rev(arr) {
var value;
var nArr = [];
for (let i = arr.length - 1; i >= 0; i--) {
value = arr[i];
for (let j = 0; j < arr.length; j++) {
nArr[j] = value;
console.log("i:", i, "j:", j, "value:", value, "nArr:", "[" + nArr + "]");
}
}
console.log("result:", "[" + nArr + "]");
}
rev(arr);