modern-web-design-and-development

(Brent) #1

jQuery also provides some utilities for dealing with the native parts of
JavaScript. This is not its main focus, mind you; libraries such as MooTools
exist for this purpose.


.merge()


merge() allows you to merge the contents of two arrays into the first
array. This entails permanent change for the first array. It does not make
a new array; values from the second array are appended to the first:


1 var arr1 = ['one', 'two'];
2 var arr2 = ['three', 'four'];
3 $.merge(arr1, arr2);

After this code runs, the arr1 will contain four elements, namely one, two,
three, four. arr2 is unchanged. (If you’re familiar with PHP, this function
is equivalent to array_merge().)


.extend()


extend() does a similar thing, but for objects:


1 var obj1 = {one: 'un', two: 'deux'}
2 var obj2 = {three: 'trois', four: 'quatre'}
3 $.extend(obj1, obj2);

extend() has a little more power to it. For one thing, you can merge more
than two objects — you can pass as many as you like. For another, it can
merge recursively. That is, if properties of objects are themselves objects,
you can ensure that they are merged, too. To do this, pass true as the first
argument:


1 var obj1 = {one: 'un', two: 'deux'}
Free download pdf