In the first case, you saved the link of one array to two variables - a
and b
. Then you changed a
, which removes the link and now contains 4
. After that, you only have a variable b
that refers to the array, and you can change the elements of this array only throughb
.
a
b
. a[a.length - (i + 1)] = b[i]
, , b
, b
.
, a[a.length - (i + 1)] = b[i]
b[i]
a[a.length - (i + 1)]
, b[b.length - (i + 1)]
.
, a
b
, a
, b
, .
, . slice
([...a]
) a.reverse
, .
const a = [0,1,2,3,4];
const b = a.slice();
for(let i = b.length - 1; i >= 0; i--) {
a[a.length - i - 1] = b[i];
}
console.log(a);
console.log(b);
Hide resultreverse
let a = [0,1,2,3,4];
let b = [...a];
a.reverse();
console.log(a);
console.log(b);
Hide result