Powerful JQuery array Encapsulation

Source: Internet
Author: User

JQuery's Array Processing is very convenient and powerful. It encapsulates a lot of functions that native js arrays cannot match in one step. Let's take a look at the strength of the JQuery array.

$. 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:

Var arr = ['javascript ', 'php', 'java', 'c ++', 'c # ', 'perl', 'vb ', 'html ', 'css ', 'Objective-C']; $. each (arr, function (key, val) {// firebug leleconsole. log ('index in arr: '+ key + ", corresponding value:" + val); // if you want to exit the loop // return false ;});

Another test program:

Var fruit = ['apple', 'Banana ', 'orange', 'cantalou', 'mango']; // use the native getElementsByTagName to obtain the object set var h2obj = document of the h2 element. 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 of alert (in the 'Fruit array, the index: '+ key +' corresponds to '+ 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;

$. 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 );

Var temp = []; temp = $. grep (arr, function (val, key) {if (val. indexOf ('C ')! =-1) return true; // if the [invert] parameter is not set or is false, $. grep only collects the array elements returned by the callback function. // otherwise, the [invert] parameter is true, $. the grep collection callback function returns an array element of false}, false); console. dir (temp );

Another test program:

// $. Grep () Filter 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 'array value is mango: '+ key) ;}}); var _ moziGt1 = $. grep (fruit, function (val, key) {return key> 1 ;}); alert ('element with an index value greater than 1 in the fruit array is '+ _ moziGt1 ); var _ cmdilt1 = $. grep (fruit, function (val, key) {return key> 1 ;}, true); // The third reliable parameter is input here, return values in the filter function are reversed by alert ('fruit array's element with an index value less than or equal to 1 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.

// Versions earlier than 1.6 only support the array temp =$. map (arr, function (val, key) {// return null, the returned array length is reduced by 1if (val = 'vb ') return null; return val ;}); console. dir (temp); // 1.6 starts to support objectvar obj = {key1: 'val1', key2: 'val2', key3: 'val3'}; temp = $. map (obj, function (val, key) {return val ;}); console. dir (temp );

Another test program:

// $. Map () converts arrays by 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) {// 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 apple is '+ _ mapArrB); alert (' is each element in the original array, expand an element that adds the character \ '[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.

// Return the position of the element in the array. 0 indicates the starting position. If-1 is returned, console. log ($. inArray ('javascript ', arr) of the element is not found ));

Test procedure:

// $. InArray determines whether the value is in the array. If no value exists,-1 is returned. If yes, the corresponding index value $ ('input # js_inarray ') is returned '). 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.

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

// $. Merge () merges 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 ('the length of the new array after merging is: '+ fruitNew. length + '. the value is '+ 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.

<Div> blahblahblah .... </div> <div class = "dup"> </div> <div class = "dup"> </div> <div class =" dup "> </div> // $. unique only supports DOM element arrays, removes duplicate DOM elements, and does not support other types of arrays (String or Number) // obtain the original DOM array, instead of var divs =$ ('div ') encapsulated by jQuery '). get (); // Add divdivs = divs whose class is dup. concat ($ ('div. dup '). get (); console. log ("before unique:" + divs. length); divs = $. unique (divs); console. log ("after unique:" + divs. length );

Test procedure:

// $. Unique () filters repeated elements in an array (DOM element arrays 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 (the original length value of 'array _ h2Arr is '+ _ curLen +', which is '+ _ newLen +' After filtering '. 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.

// $. 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.

// $ (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 restored: '+ _ toArr. constructor. name );});

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.