JQuery Array Processing (including instance demonstration)

Source: Internet
Author: User

1. $. each (array, [callback]) traversal [common]
Explanation: Unlike the $ (). each () method of the jQuery object, this method can be used to sample any object (not just an array ~). 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:
Copy codeThe Code is as follows:
Var _ mozi = ['mojie', 'mozi', 'mozi', 'both love and not attacking ', 'shang Tong Shang Xian']; // The array used in this article, the same below
$. Each (_ mozi, 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 '_ mozi array, the index:' + key + 'corresponds to the value:' + val );
});

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;
2. $. grep (array, callback, [invert]) Filter Arrays [common]
Explanation: 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:
$. Grep (_ mozi, function (val, key ){
// The filter function has two parameters: the first is the current element and the second is the element index.
If (val = 'mozi '){
Alert (the subscript of 'array value is: '+ key );
}
});

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

Var _ moziLt1 = $. grep (_ mozi, 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 '_ mozi array is' + _ moziLt1 );

3. $. map (array, [callback]) converts arrays by given conditions [general]
Explanation: 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 often 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:
Var _ mapArrA = $. map (_ mozi, function (val ){
Return val + '[new addition]';
});
Var _ mapArrB = $. map (_ mozi, function (val ){
Return val = 'mozi '? '[Add only to Mozi]' + val: val;
});
Var _ mapArrC = $. map (_ mozi, 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 only adding characters to the element Mozi 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 );

4. $. inArray (val, array) Determine whether the value exists in the array [common]

Explanation: determine the position of the first parameter in the array and start counting from 0 (if not found, return-1 ).
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:
Var _ exist = $. inArray ('mozi ', _ mozi );
Var _ inexistence = $. inArray ('wei Yang ', _ mozi)
If (_ exist> = 0 ){
Alert ('mozi exists in array _ mozi, and its index value in the array is '+ _ exist );
}
If (_ inexistence <0 ){
Alert ('wei Yang does not exist in array _ mozi !, Returned value: '+ _ inexistence + '! ');
}

5. $. merge (first, second) merge two arrays [general]
Explanation: 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:
// Native concat () may be more concise than it
_ Effecinew = $. merge (_ mozi, ['guimigu ', 'shangyang', 'sunning', 'ponjuan ', 'suqin', 'zhangyi '])
Alert ('length of the new array after merging is '+ _ moziNew. length +'. Value: '+ _ moziNew );

6. $. unique (array) filters repeated elements in the array [not commonly used]
Explanation: delete repeated elements in an array. Only the DOM element array can be deleted, but the string or number array cannot be 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:
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 all' + (_ curLen-_ newLen) + 'repeated elements ')

7. $. makeArray (obj) converts class array objects to arrays [not commonly used]
Explanation: 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.
Copy codeThe Code is as follows:
Var _ makeArr = $. makeArray (h2obj );
Alert ('h2 element object set data type conversion: '+ _ makeArr. constructor. name); // output Array

8. $ (dom). toArray () Restore all DOM elements to an array [not commonly used]
Explanation: restores all DOM elements in the jQuery set to an array;
This method is not commonly used. I even think it is as redundant as $. makeArray.
Copy codeThe Code is as follows:
Var _ toArr = $('h2 '). toArray ();
Alert (the data type after the 'h2 element set is recovered: '+ _ toArr. constructor. name );

DEMO code: after running, you need to refresh it.
<! Doctype html> <pead> <meta charset = "gbk"> <title> jQuery Array Processing (including instance Demonstration) @ Mr. think </title> <style>/* reset css */body {font-size: 0.8em; font-family: \ 5fae \ 8f6f \ 96c5 \ 9ed1; line-height: 1.8em} div, h2, p, fieldset, legend, span, em, dl, dt, dd {margin: 0; padding: 0} input {font: 12px/1.5 tahoma, arial, sans-serif; vertical-align: middle} h1 {font-size: 1em; font-weight: normal} h1 a {background: #047; padding: 2px 3px; color: # fff; Text-decoration: none} h1 a: hover {background: # a40000; color: # fff; text-decoration: underline} h3 {color: #888; font-weight: bold; font-size: 1em; margin: 1em auto; position: relative}/* demo css */# demo {width: 600px; margin-bottom: 100px} h2 {line-height: 24px; font-size: 16px; font-weight: normal;} h2 span {margin-right: 30px; padding: 3px 10px; background: # D2D9DF; letter-spacing: 1px} pre {margin-bottom: 20px; padding: 10px; bac Kground: # eee; border: 1px solid # ccc; line-height: 18px} </style> <meta name = "author" content = "Mr. think qingbird "/> <meta name =" keywords "content =" Mr. think, front-end development, WEB front-end, front-end technology, front-end development, WEB front-end development, user experience, Website planning, website optimization, qingbird, javascript, jQuery, css, xhtml, html, UE, SEO, Mr. think blog, qingbird blog, PHP enthusiast, Bluebirdsky "/> <meta name =" description "content =" Mr. think's blog, named qingbird, is now focused on WEB Front-end development and is also a PHP enthusiast. love thinking, a little code cleanliness, raw crab legs, love meat. here is where I record knowledge and things in my life. "/> <l Ink rel = "pingback" href = "http://mrthink.net/xmlrpc.php"/> <link rel = "alternate" type = "application/rss + xml" title = "Mr. think blog RSS Feed "href =" http://mrthink.net/feed/ "/> </pead> <body> Array Used for demonstration <pre> var _ mozi = ['mojia ', 'mozi ', 'Mo Yun ', 'both non-attacking', 'shang Tong Shang Xian ']; </pre> 1. $. each traversal example [common] <input type = "button" id = "js_each" value = "run"/> <pre >$. each (_ mozi, function (key, val) {// The callback function has two parameters. The first is the element index, and the second is the current value in the alert ('_ mozi array, Index: '+ key +' corresponds to '+ val) ;}); </pre> 2. $. grep () filters arrays [commonly used] <input type = "button" id = "js_grep" value = "run"/> <pre >$. grep (_ mozi, function (val, key) {// The filter function has two parameters: the first is the current element, and the second is the element index if (val = 'mozi ') {alert (the subscript of 'array value is: '+ key) ;}}); var _ moziGt1 = $. grep (_ mozi, function (val, key) {return key> 1 ;}); alert (the element whose index value is greater than 1 in the '_ mozi array is: '+ _ moziGt1); var _ moziLt1 = $. grep (_ mozi, function (val, key) {return key> 1 ;}, true); // This The third reliable parameter is input, and the return value of the filter function is reversed by alert ('_ mozi array's element with an index value less than or equal to 1 is' + _ effecilt1 ); </pre> 3. $. map () converts arrays by given conditions [general] <input type = "button" id = "js_map" value = "run"/> <pre> var _ mapArrA = $. map (_ mozi, function (val) {return val + '[new addition]';}); var _ mapArrB = $. map (_ mozi, function (val) {return val = 'mozi '? '[Add only to Mozi]' + val: val;}); var _ mapArrC = $. map (_ mozi, function (val) {// expands a new element return [val, (val + '[extension]')] For the array element;}); alert ('the array after each element is appended with the \ '[new addition] \' character is: '+ _ mapArrA ); alert ('the array after only adding characters to the element Mozi is '+ _ mapArrB); alert (' is each element in the original array, expand an element that adds the character \ '[new] \', and the returned array is '+ _ mapArrC); </pre> 4. $. inArray () determine whether the value exists in the array [commonly used] <input type = "button" id = "js_inarray" value = "run"/> <pre> var _ exist = $. inArray ('mozi ', _ mozi); var _ inexistence = $. InArray ('wei Yang ', _ mozi) if (_ exist> = 0) {alert ('mozi exists in array _ mozi, and its index value in the array is: '+ _ exist);} if (_ inexistence <0) {alert ('wei Yang does not exist in array _ mozi !, Returned value: '+ _ inexistence + '! ') ;}</Pre> 5. $. merge () merges two arrays [general] <input type = "button" id = "js_merge" value = "run"/> <pre> // native concat () it may be more concise than it. _ moziNew = $. merge (_ mozi, ['guimigu ', 'shangyang', 'sunning', 'ponjuan ', 'suqin', 'zhangyi ']) alert ('the length of the new array after merging is '+ _ moziNew. length + '. the value is '+ _ moziNew); </pre> 6. $. unique () filters repeated elements in the array [not commonly used] <input type = "button" id = "js_unique" value = "run"/> <pre> var _ h2Arr = $. makeArray (h2obj); // repeat array _ h2Arr once _ h2Arr = $. merge (_ h2Arr, _ h2Arr); var _ curLen = _ h2Arr. length; _ h2Arr = $. unique (_ h2Arr); var _ newLen = _ h2Arr. length; alert (the original length value of 'array _ h2Arr is '+ _ curLen +', which is '+ _ newLen +' After filtering '. filter '+ (_ curLen-_ newLen) + 'repeated elements') </pre> 7. $. makeArray () class array object to array [not commonly used] <input type = "button" id = "js_makearray" value = "run"/> <pre> var _ makeArr = $. makeArray (h2obj); alert ('h2 element object set data type conversion: '+ _ makeArr. constructor. name); </pre> 8. $. toArray () restore all DOM elements to an array [not commonly used] <input type = "button" id = "js_toarray" value = "run"/> <pre> var _ toArr = $ (' h2 '). toArray (); alert (the data type after the 'h2 element set is restored: '+ _ toArr. constructor. name); </pre> </body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
From Mr. Think's blog: http://mrthink.net/jquery-array-eachgrepinarray/

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.