Click here to Skip to main content
14,454,989 members
Rate this:
Please Sign up or sign in to vote.
See more:
hey guys , got this weird bug,
I've created a new array from an existing array,
however when i update the objects in said copied array,
the objects in the original array are being updated as-well,
the reference shouldn't be the same so i have no idea why this is happening
the currentShape Array is an array containing 4 objects in total

the code:
function checkKey(e) {
  nextShape = [...currentShape];
  e.preventDefault();
  e = e || window.event;
  if (e.keyCode === 40) {
    direction = "down";
    nextShape.forEach(cell => cell.i++);
  drawShape();
}

drawShape is irrelevant since it already gets a modified array which isnt what its supposed to get,

What I have tried:

tried using slice,map to creat the new array, same effect
Posted
Updated 14-Feb-20 3:59am
v2
Comments
Gerry Schmitz 13-Feb-20 20:42pm
   
"Copying" is not the same as "cloning". Copying creates references to existing objects. Cloning creates new objects with their own references.
Richard Deeming 14-Feb-20 8:46am
   
You've tagged this question as "Java", but your code appears to be "Javascript".

Despite the similar names, these are two completely separate languages.
Rate this:
Please Sign up or sign in to vote.

Solution 1

What you are seeing is an example of Variable Assignment, which basically says that the 2 variables are equal.
What I think you want to do is to use the clone() method, which will make a new variable and duplicate the values from the old variable.

Reference:
Array Copy in Java[^]
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

   
Rate this:
Please Sign up or sign in to vote.

Solution 3

Quote:
New array effect old array, even tho I copied it and not used the same refrence

Rule of thumb: in managed languages, anything that not a generic type (strings, arrays, objects) is copied by reference if you don't specify otherwise.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100