📅  最后修改于: 2023-12-03 15:02:09.636000             🧑  作者: Mango
在jQuery中,extend()
方法用于将一个或多个对象的内容合并到目标对象中。这个方法可用于合并任意数量的对象,且只要有一个参数为 true,则整个操作变为深层合并。
jQuery.extend(target [, object1 ] [, object2 ] [, objectN ])
参数说明:
target
:必需。目标对象,可以是任意类型的对象。object1
:可选。第一个被合并的对象。object2
:可选。第二个被合并的对象。objectN
:可选。第 N 个被合并的对象。// 合并两个对象
var obj1 = {name: '张三', age: 20, sex: '男'};
var obj2 = {age: 22, address: '北京', sex: '女'};
var target = {};
jQuery.extend(target, obj1, obj2);
alert(JSON.stringify(target));
// 输出:{"name":"张三","age":22,"sex":"女","address":"北京"}
// 合并多个对象
var obj1 = {name: '张三', age: 20, sex: '男'};
var obj2 = {age: 22, address: '北京', sex: '女'};
var obj3 = {name: '李四', age: 25, address: '上海', sex: '男'};
var obj4 = {name: '王五', age: 30, address: '广州', sex: '女', hobby: '唱歌'};
var target = {};
jQuery.extend(target, obj1, obj2, obj3, obj4);
alert(JSON.stringify(target));
// 输出:{"name":"王五","age":30,"sex":"女","address":"广州","hobby":"唱歌"}
// 深层合并
var obj1 = {person: {name: '张三', age: 20, sex: '男'}};
var obj2 = {person: {age: 22, address: '北京', sex: '女'}};
var target = {};
jQuery.extend(true, target, obj1, obj2);
alert(JSON.stringify(target));
// 输出:{"person":{"name":"张三","age":22,"sex":"女","address":"北京"}}