Jquery array encapsulation usage method sharing (jquery array traversal)

Source: Internet
Author: User

$. Each (array, [callback]) Traversal

Unlike the $. each () method of the jQuery object, this method can be used to sample all objects (not just arrays ~). The callback function has two parameters: the first is the object's member or array index, and the second is the corresponding variable or content. if you want to exit the each loop, the callback function returns false. Other return values are ignored.

Each traversal is a variant of the for Loop in normal event processing, but it is more powerful than the for loop. in the array, it can easily obtain the array index and the corresponding value. example:

The usage is as follows:
Copy codeThe Code is as follows:
Var arr = ['javascript ', 'php', 'java', 'c ++', 'c # ', 'perl', 'vb ', 'html ', 'css ', 'Objective-C'];
$. Each (arr, function (key, val ){
// Firebug console
Console. log ('index in arr: '+ key + ", corresponding value:" + val );
// If you want to exit the loop
// Return false;
});

Another test program:
[/Code]
Var fruit = ['apple', 'Banana ', 'orange', 'cantalou', 'mango'];
// Use the native getElementsByTagName to obtain the object set of the h2 Element
Var h2obj = document. getElementsByTagName ('h2 ');

// $. Each () traverses the Array
$ ('Input # js_each '). click (function (){
$. Each (fruit, function (key, val ){
// The callback function has two parameters: the first is the element index and the second is the current value.
Alert (in the 'Fruit array, the index: '+ key +' corresponds to the value: '+ val );
});
});

[/Code]
Compared with native for... in, each is stronger. for... in can also traverse the array and return the corresponding index, but the value needs to be obtained through arrName [key;

$. Grep (array, callback, [invert]) Filter

Filter Array elements using the filter function. this function must pass at least two parameters (the third parameter is true or false, and the return value of the filter function is reversed, which is of little use): the array to be filtered and the filter function. the filter function must return true to retain the element or false to delete the element. in addition, the filter function can also be set as a string (which is not recommended for personal users and can be checked by themselves );
Copy codeThe Code is as follows:
V [code] ar temp = [];
Temp = $. grep (arr, function (val, key ){
If (val. indexOf ('C ')! =-1)
Return true;
// If the [invert] parameter is not set to false or is set to false, $. grep only collects array elements returned by the callback function.
// If the [invert] parameter is true, $. grep collects the array elements that the callback function returns false.
}, False );
Console. dir (temp );

Another test program:
Copy codeThe Code is as follows:
// $. Grep () filter the Array
$ ('Input # js_grep '). click (function (){
$. Grep (fruit, function (val, key ){
// The filter function has two parameters: the first is the current element and the second is the element index.
If (val = 'mango '){
Alert ('the subscript of the array value mango is: '+ key );
}
});

Var _ moziGt1 = $. grep (fruit, function (val, key ){
Return key> 1;
});
Alert (the element with an index value greater than 1 in the 'Fruit array is '+ _ moziGt1 );

Var _ partition ilt1 = $. grep (fruit, function (val, key ){
Return key> 1;
}, True );
// The third reliable parameter is input here, which is used to reverse the return value in the filter function.
Alert (the element with the index value less than or equal to 1 in the 'Fruit array is '+ _ effecilt1 );
});

$. Map (array, [callback]) converts arrays based on given conditions

The conversion function as a parameter is called for each array element, and a converted element is passed to the conversion function as a parameter. the conversion function can return the converted value, null (delete items in the array), or an array containing values, and extend it to the original array. this is a very powerful method, but it is not commonly used. it can update array element values based on specific conditions, or expand a new copy element based on the original value.
Copy codeThe Code is as follows:
// Versions earlier than 1.6 only support Arrays
Temp = $. map (arr, function (val, key ){
// Return null, and the returned array length is reduced by 1
If (val = 'vb ') return null;
Return val;
});
Console. dir (temp );
// Object in json format is supported starting from 1.6
Var obj = {key1: 'val1', key2: 'val2', key3: 'val3 '};
Temp = $. map (obj, function (val, key ){
Return val;
});
Console. dir (temp );

Another test program:
Copy codeThe Code is as follows:
// $. Map () converts arrays based on given conditions
$ ('Input # js_map '). click (function (){
Var _ mapArrA = $. map (fruit, function (val ){
Return val + '[new addition]';
});
Var _ mapArrB = $. map (fruit, function (val ){
Return val = 'apple '? '[Add only to Apple]' + val: val;
});
Var _ mapArrC = $. map (fruit, function (val ){
// Expand a new element for the array element
Return [val, (val + '[extension]')];
});
Alert ('the array after each element is appended with the \ '[new addition] \' character is: '+ _ mapArrA );
Alert ('the array after adding characters only to the element apple is '+ _ mapArrB );
Alert ('for each element in the original array, extend an element that adds the character \' [add new] \ ', and the returned array is' + _ mapArrC );
});

$. InArray (val, array) determines whether the value exists in the array

Determine the position of the first parameter in the array and start counting from 0 (if not found,-1 is returned). Do you remember the indexOf () method? IndexOf () returns the first occurrence position of the string, while $. inArray () returns the position of the input parameter in the array. Similarly, if found, a value greater than or equal to 0 is returned. If not found,-1 is returned. now, you know how to use it. with it, it becomes easy to determine whether a value exists in an array.
Copy codeThe Code is as follows:
// Return the position of the element in the array. 0 indicates the starting position. If-1 is returned, the element is not found.
Console. log ($. inArray ('javascript ', arr ));


Test procedure:
[Code]
// $. InArray: determines whether the value is in the array.-1 is returned if no value exists. If yes, the corresponding index value is returned.
$ ('Input # js_inarray'). click (function (){
Var _ exist = $. inArray ('mango ', fruit );
Var _ inexistence = $. inArray ('durian', fruit)
If (_ exist> = 0 ){
Alert ('mango exists in the array fruit, and its index value in the array is: '+ _ exist );
}
If (_ inexistence <0 ){
Alert ('durian does not exist in the array fruit !, Returned value: '+ _ inexistence + '! ');
}
});

$. Merge (first, second) combines two Arrays

The returned result modifies the content of the first array. The elements of the first array are followed by the elements of the second array. this method replaces the native concat () method with the jQuery method, but the function is not concat () Powerful. concat () can merge multiple arrays at the same time.
Copy codeThe Code is as follows:
Var frontEnd = ['javascript ', 'css', 'html '],
BackEnd = ['java', 'php', 'c ++ '];
// This method modifies the first parameter, that is, the frontEnd array.
Temp = $. merge (frontEnd, backEnd );
Console. dir (temp );
Console. dir (frontEnd );
// You can use the following method to avoid the impact on the original array.
// $. Merge ($. merge ([], frontEnd), backEnd );

Test procedure
Copy codeThe Code is as follows:
// $. Merge () combines two Arrays
$ ('Input # js_merge'). click (function (){
// Native concat () may be more concise than it
FruitNew = $. merge (fruit, ['peach ', 'Dragon go', 'watermelon', 'carambola ', 'lychee', 'longan '])
Alert ('length of the new array after merging is '+ fruitNew. length +'. Value: '+ fruitNew );
});

$. Unique (array) filters repeated elements in the array

Deletes repeated elements in the array. only the DOM element array is deleted, but the string or number array is not processed. the first time I saw this method, I thought it was a very convenient method. It can be used to filter duplicates. What a perfect method is, but if I take a closer look, I can only process DOM elements. off. therefore, I defined it as an uncommon element. At least, I have never used it since I used jQuery.

Copy codeThe Code is as follows:
<Div> blahblahblah... </div>
<Div> </div>
<Div class = "dup"> </div>
<Div class = "dup"> </div>
<Div class = "dup"> </div>
<Div> </div>
// $. Unique only supports DOM element arrays and removes duplicate DOM elements. Other types of arrays (String or Number) are not supported)
// Obtain the original DOM array instead of the one encapsulated by jQuery
Var divs = $ ('div '). get ();
// Add a few divs whose class is dup
Divs = divs. concat ($ ('div. dup'). get ());
Console. log ("before unique:" + divs. length );
Divs = $. unique (divs );
Console. log ("after unique:" + divs. length );

Test procedure:
Copy codeThe Code is as follows:
// $. Unique () filters repeated elements in the array (DOM element array only)
$ ('Input # js_unique '). click (function (){
Var _ h2Arr = $. makeArray (h2obj );
// Repeat array _ h2Arr once
_ H2Arr = $. merge (_ h2Arr, _ h2Arr );
Var _ curLen = _ h2Arr. length;
_ H2Arr = $. unique (_ h2Arr );
Var _ newLen = _ h2Arr. length;
Alert ('array _ h2Arr original length value: '+ _ curLen +', after filtering: '+ _ newLen + '. filter '+ (_ curLen-_ newLen) + 'repeated elements ');
});

$. MakeArray (obj) converts class array objects to Arrays

Converts a class array object to an array object. The class array object has the length attribute, and its member index is 0 to length-1. this is a redundant method. The omnipotent $ already contains this function. the official jQuery website is very vague. in fact, it is to convert a class array object (for example, the element object set obtained using getElementsByTagName) into an array object.

First, what is a class array object? The jQuery official website uses divs = getElementsByTag ('div ') as an example. This divs has some methods similar to arrays, such as length, element acquisition through [index], and then $. if makeArray (divs) converts it to an array, other functions of the array can be used, such as reverse () and pop.
Copy codeThe Code is as follows:
// $. MakeArr () Class array Conversion
$ ('Input # js_makearray'). click (function (){
Var _ makeArr = $. makeArray (h2obj );
Alert ('h2 element object set data type conversion: '+ _ makeArr. constructor. name );
});

$ (Dom). toArray () restores all DOM elements to an array

Restores all DOM elements in the jQuery set to an array. This is not a common method. I even think it is as redundant as $. makeArray.
Copy codeThe Code is as follows:
// $ (Dom). toArray () restores all DOM elements to an array
$ ('Input # js_toarray'). click (function (){
Var _ toArr = $('h2 '). toArray ();
Alert (the data type after the 'h2 element set is recovered: '+ _ toArr. constructor. name );

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.