jQuery.extend()方法
定义
jQuery.extend()方法用于将一个或多个对象合并到目标对象(第一个形参)中
语法
$.extend( target [, object1 ] [, objectN ] )
深度合并deep为true:且多个对象的某个同名属性也都是对象,则该"属性对象"的属性也将进行合并。
$.extend( [deep ], target, object1 [, objectN ] )
示例
//obj2 合并到 obj1 中
var obj1 = {name: "zhangsan"},obj2 = {name: "李四",age: 18};
jQuery.extend(obj1, obj2);
console.log(obj1); //{name: '李四', age: 18}
深度合并
var obj1 = {
hobby: {
weekend: "cooking"
}
},
obj2 = {
name: "李四",
age: 18,
hobby: {
am: "sleep",
pm: "game"
}
};
//深度合并
$.extend(true, obj1, obj2);
console.log(obj1);//hobby: {weekend: 'cooking', am: 'sleep', pm: 'game'}, name: '李四', age: 18}
//deep=false
$.extend(obj1, obj2);
console.log(obj1);//hobby: { am: 'sleep', pm: 'game'}, name: '李四', age: 18}
//*可以看到weekend: 'cooking'被覆盖了*/