If b = a, why does b change after overriding a in the next line?

Can someone explain the difference between the two scenarios? Namely, why b was not redefined in the first, but it was redefined in the second?

a = [0,1,2,3,4]
b = a           //b = [0,1,2,3,4]
a = 4     
console.log(b)  //b is still [0,1,2,3,4]
                //redefining a AFTER saying b = a will NOT change b

/

a = [0,1,2,3,4]
b = a           //b = [0,1,2,3,4]

for ( i = 0; i < a.length; i++){
  a[a.length - (i + 1)] = b[i]  
}               //I though this loop would redefine a as b in reverse. But this happens: 

console.log(a)  //both a and b have changed to [0,1,2,1,0]
console.log(b)  //I don't understand why b changed at all, since a is being redefined
                //AFTER I saved b as [0,1,2,3,4] and the = sign is supposed to just
                //assign the value on the right to the value on the left
+4
source share
2 answers

In the first case, you saved the link of one array to two variables - aand b. Then you changed a, which removes the link and now contains 4. After that, you only have a variable bthat 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(); // splice returns a new array

for(let i = b.length - 1; i >= 0; i--) {
   a[a.length - i - 1] = b[i];
}

console.log(a);
console.log(b);
Hide result

reverse

let a = [0,1,2,3,4];
let b = [...a];
a.reverse();

console.log(a);
console.log(b);
Hide result
+3

:

1

a = [0,1,2,3,4]

Ref#1 = [0,1,2,3,4]
a = Ref#1

b = a,

b = Ref#1

a = 4

Ref#2 = 4
a = ValOfRef#2

b Ref#1, [0,1,2,3,4]. , , Number , value Objects/Arrays - refrence.

2

tt Ref#1 , a b holde Ref#1, . refrence a b. - JSON.parse(JSON.strigify()). .

a = [0, 1, 2, 3, 4]
b = JSON.parse(JSON.stringify(a));

for (i = 0; i < a.length; i++) {
  a[a.length - (i + 1)] = b[i];
}

console.log(a);
console.log(b);
Hide result
+1

Source: https://habr.com/ru/post/1690830/


All Articles