javascript - jQuery - $.extend deep loses reference to array -
i have observed odd issue in jquery's $.extend
method , referencing array (which considered object in javascript).
i use defaults object, defined follows:
var defaults = { numbers: [] };
i have config option pass function, defined follows:
var config = { numbers: [1, 2, 3] };
within function, extend these 2 (using deep $.extend
):
function configure(settings) { var nums = $.extend(true, {}, defaults, settings); nums.numbers.push(4); console.log(settings, nums); } configure(config);
when log these two, results follows:
settings: {"numbers":[1,2,3]} nums: {"numbers":[1,2,3,4]}
what failing understand is, jquery merges objects left right.
i expect since settings last object extended, numbers array that's created in nums
reference settings.numbers
(since settings
last object $.extend
ed). not case (as can see when log final results).
can please explain why? cause of difficult find bug in app want ensure understand not happen again.
you made deep merge:
on deep extend, object , array extended
the target object first object after deep
boolean.
in case, it's {}
, nums
because of assignation.
settings
isn't target object. numbers
array therefore not 1 of nums
.
Comments
Post a Comment