Bug Tracker

Modify

Ticket #2820 (closed bug: fixed)

Opened 5 years ago

Last modified 5 years ago

$.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:
Blocking: Blocked by:

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

comment:1 Changed 5 years ago by flesler

  • Owner set to flesler
  • Status changed from new to assigned

comment:2 Changed 5 years ago by flesler

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

comment:3 Changed 5 years ago by flesler

  • Status changed from assigned to closed
  • Resolution set to fixed

Fixed at [5599].

Please follow the  bug reporting guidlines and use  jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

View

Add a comment

Modify Ticket

Action
as closed
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.