Click here to Skip to main content
15,895,423 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:
JavaScript
function checkKey(e) {
  nextShape = [...currentShape];
  e.preventDefault();
  e = e || window.event;
  if (e.keyCode === 40) {
    direction = "down";
    nextShape.forEach(cell => cell.i++);
JavaScript
  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 2:59am
v2
Comments
[no name] 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.

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[^]
 
Share this answer
 
 
Share this answer
 
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.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900