我试图使用jQuery $ .extend合并两个对象.
使用以下代码,我试图提醒("Ball - Stump - Umpire").但目前的输出是("Undefined - Stump - Umpire").它没有实现深度(递归)副本.我们如何纠正这个?
$(document).ready(function () {
debugger;
//$.extend
var obj3 = { throwable: { text1: 'Ball' }, text3: 'Umpire' };
var obj4 = { throwable: { text4: 'Bat' }, text2: 'Stump' }
//Simple Copy
var result1 = $.extend(obj3, obj4);
//alert(result1.throwable.text4 + " - " + result1.text2 + " - " + result1.text3);
//Deep Copy
//First parameter is passed as Boolean true to accomplish deep (recursive) copy
var result2 = $.extend(true, obj3, obj4);
alert(result2.throwable.text1 + " - " + result2.text2 + " - " + result2.text3);
});
Run Code Online (Sandbox Code Playgroud)
编辑:我提到了
你的第二个代码片段不会如预期进行的深拷贝工作obj4到obj3,当单独运行.
问题是,前面的代码片段已经执行了一个浅表的obj4into obj3,完全覆盖了其throwable成员obj4的过程.因此,在代码运行之后throwable.text1不再存在obj3.
最初obj3是:
{ throwable: { text1: 'Ball' }, text3: 'Umpire' }
Run Code Online (Sandbox Code Playgroud)第一个代码段运行后,obj3变为:
{ throwable: { text4: 'Bat' }, text3: 'Umpire', text2: 'Slump' }
Run Code Online (Sandbox Code Playgroud)最后,在第二个代码片段运行后,obj3仍然是:
{ throwable: { text4: 'Bat' }, text3: 'Umpire', text2: 'Slump' }
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
6949 次 |
| 最近记录: |