Side navigation
#2820 closed bug (fixed)
Opened May 07, 2008 09:06PM UTC
Closed May 14, 2008 07:46PM UTC
$.extend not deep copying arrays
Reported by: | david.wood | Owned by: | flesler |
---|---|---|---|
Priority: | major | Milestone: | 1.2.4 |
Component: | core | Version: | 1.2.3 |
Keywords: | Cc: | ||
Blocked by: | Blocking: |
Description
When using $.extend to deep copy an object with an array, the array is copied by reference, which is not a true deep copy.
In the following example, there is an object named defaults that is used to to initialize working objects. The object contains a single property, sequence, that is an array.
var defaults = { sequence: [] };
The defaults object is then deep copied to another variable, named working, to which 10 items are then added.
var working = $.extend(true, {}, defaults); for (var i = 0; i < 10; i++) { working.sequence.push("item " + i); }
Checking working.sequence.length will return a length of 10, which is expected. However, defaults.sequence.length will also return a length of 10, as the sequence property of defaults is copied by reference.
To resolve this issue and force an array property to not copy by reference with a deep copy, replace line 603 with:
target[ name ] = deep && options[ name ] instanceof Array ? options[ name ].slice(0) : options[ name ];