Currently, I am delving into JavaScript in regards to array assignment and cloning. A puzzling issue arises when attempting to clone the elements of array A into array B using the spread operator "...". Surprisingly, when modifying the elements in array B, the elements in array A also seem to be affected.
For instance:
A = [{id:1, value:3},{id:2, value:1}];
B = [...A];
B[0].value = 4;
console.log(A[0].value);//the output changes to 4, not 3
I've noticed that this issue does not occur when cloning a regular array:
A = [3, 1];
B = [...A];
B[0] = 4;
console.log(A[0]);//the output is still 3
It is known that one purpose of cloning in JavaScript is to prevent two variables from referencing the same memory location. However, why does altering an element in array B reflect on array A as well? If there are any misconceptions on my part, I would appreciate your guidance in clearing them up. Alternatively, if this problem has been addressed and resolved in past discussions, kindly share the relevant link.