jQuery: The Write Less, Do More JavaScript Library

Ticket #2820 (closed bug: fixed)

Opened 3 months ago

Last modified 3 months ago

$.extend not deep copying arrays

Reported by: david.wood Assigned to: flesler
Type: bug Priority: major
Milestone: 1.2.4 Component: core
Version: 1.2.3 Keywords:
Cc: Needs: Review

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

Attachments

Change History

Changed 3 months ago by flesler

  • owner set to flesler
  • status changed from new to assigned

Changed 3 months ago by flesler

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

Changed 3 months ago by flesler

  • status changed from assigned to closed
  • resolution set to fixed

Fixed at [5599].

Note: See TracTickets for help on using tickets.