0

So apparently when using javascript to make a copy of an array copies a reference and so I get pass by reference issues. Good to know.

So how do I copy an array of objects (a class effectively) without passing by reference. I tried using slice but it didnt work.

Thanks.

discodowney
  • 1,475
  • 6
  • 28
  • 58
  • Show us the code of what you tried – Sara Fuerst Feb 13 '17 at 15:56
  • 1
    See also [How do you clone an Array of Objects in Javascript](http://stackoverflow.com/questions/597588/how-do-you-clone-an-array-of-objects-in-javascript) – Mike Cluck Feb 13 '17 at 15:58
  • @charlietfl `slice` makes a deep copy only when copying primitive values. – Teemu Feb 13 '17 at 16:00
  • Well initially I didnt know this was how it worked so I was just assigning my new array to the existing one. Then I tried slice. Then I google but most just mention slice for primitive arrays but nothing for non primative. Ill update the original post – discodowney Feb 13 '17 at 16:00
  • 1
    In JS assigning a pre-existing object to a variable results in it being a reference to the same object - if wanting to clone all objects there's various approaches to deep copies as there really is no generic method of cloning objects for simple objects `JSON.parse(JSON.stringify(obj))` may work but it will not handle methods and may not work if there are circular references. Code examples or more detail on what you're trying to clone may help us help you. – Brian Feb 13 '17 at 16:01
  • Cheers for the help. the JSON methods mentioned above done the job. I had no idea pass by reference was used in js. Thanks again – discodowney Feb 13 '17 at 16:07

0 Answers0