jQuery.extend()Method

jQuery 杂项方法jQuery Miscellaneous Methods

Examples

Iterate over array elements and modify the first object

<div id="log"></div> <script> $(function () { var object1 = { apple: 0, banana: {weight: 52, price: 100}, cherry: 97 }; var object2 = { banana: {price: 200}, durian: 100 }; /*Merge object2 into object1*/ $.extend(object1, object2); var printObj = typeof JSON != "undefined" ? JSON.stringify : function(obj) { var arr = []; $.each(obj, function(key, val) { var next = key + ": "; next += $.isPlainObject(val) ? printObj(val) : val; arr.push( next ); }); return "{ " + arr.join(", ") + " }"; }; $("#log").append( printObj(object1) ); }) </script>

Try it »

Definition and Usage

The jQuery.extend() function is used to merge the contents of one or more objects into the target object.

Note:1. If only one parameter is specified for $.extend(), it means the target parameter is omitted. At this point, target is the jQuery object itself. In this way, we can add new functions to the global object jQuery.
2. If multiple objects have the same property, the latter will override the former's property value.


Syntax

$.extend( target [, object1 ] [, objectN ] )

Indicates whether to deep merge


$.extend( [deep ], target, object1 [, objectN ] )

Warning:Passing false as the first parameter is not supported.

Parameters Description
deep Optional. Boolean type. Indicates whether to deeply merge objects. Defaults to false. If this value is true, and a property with the same name in multiple objects is also an object, then the properties of that "property object" will also be merged.
target Object type. The target object, to which member properties of other objects will be attached.
object1 Optional. Object type. The first object to be merged.
objectN Optional. Object type. The Nth object to be merged.


实例

More Examples

Merge two objects recursively
Recursively merge two objects and modify the first object.

Merge the defaults and options objects
Merge the defaults and options objects without modifying the defaults object. This is a common plugin development pattern.


jQuery 杂项方法jQuery Miscellaneous Methods

Other Extensions