0

I'm not sure how to explain this question, so I'll illustrate with code.

var bob = {
    "1": ["a", "b"]
}

var jim = bob[1]

jim.shift()

print(bob[1])

Running this with d8, I get an output of [b].

Notice how bob (the object I am referencing from jim) is being changed when I modify jim. I would like to have behavior where modifying jim does nothing to bob. That is, even after the shift(), I'd like bob[1] to still be [a,b] instead of [b]. I'm sure that this is a well-documented part of JS, but I wasn't sure how to search for it. Thanks for your help.

goodcow
  • 4,495
  • 6
  • 33
  • 52

2 Answers2

2

Make a copy of bob[1]

var bob = {
    "1": ["a", "b"]
}

var jim = bob[1].slice(0)

jim.shift()

print(bob[1])
Patrik Oldsberg
  • 1,540
  • 12
  • 14
1

Object values in JavaScript are references, not complete objects-as-values. When you assign bob[1] to jim, both jim and bob[1] reference the same object (the array). Changing the array via one reference does not affect the other reference; they're both pointing to the same (changed) array.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • How can I get the behavior that I want? Do I have to clone the object or something? Or is there a way to remove the reference? – goodcow Jul 16 '14 at 23:54
  • Yes, cloning the object is a solution. – Dested Jul 16 '14 at 23:54
  • 2
    @goodcow yes, you'd have to clone the object yourself. For arrays, you could use `jim = bob[1].slice(0);` - be aware that cloning objects is, in general, a hard problem to solve. You're also better off *avoiding* copying objects when possible, since it's clearly not free (in terms of performance). – Pointy Jul 16 '14 at 23:55
  • So generally, it's better to clone the fields of an object, not the object itself? – goodcow Jul 17 '14 at 00:04
  • @goodcow well the problem is that it's got the potential to get really messy. In this case, it's simple, so there's no problem. For more complicated objects, however, what to copy and how to copy it can be hard to figure out; there's no good general-purpose always-works solution, in other words. – Pointy Jul 17 '14 at 00:07