Bug Tracker

Opened 12 years ago

Closed 12 years ago

#2820 closed bug (fixed)

$.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 ];

Change History (3)

comment:1 Changed 12 years ago by flesler

Owner: set to flesler
Status: newassigned

comment:2 Changed 12 years ago by flesler

The diff at #1562 (if correct) should handle that.

comment:3 Changed 12 years ago by flesler

Resolution: fixed
Status: assignedclosed

Fixed at [5599].

Note: See TracTickets for help on using tickets.