Some operations summary of jquery array

Source: Internet
Author: User

jquery array processing is very convenient and powerful, one step packaging a lot of native JS arrays can not be matched to the function. Here's a look at where the power of the jquery array is.

$.each (Array, [callback]) traversal

Unlike the $.each () method of the JQuery object, this method can be used to sample any object (not just an array oh ~). The callback function has two parameters: the first is the index of the object's member or array, and the second is the corresponding variable or content. If you need to exit each loop so that the callback function returns false, the other return values are ignored.

Each traversal, I believe, is not strange, in the ordinary event processing, is a variant of the For loop, but more powerful than for loop. In the array, it can easily take the array index and the corresponding value. Example:

Here's how to use it:

1    var arr = [' JavaScript ', ' php ', ' Java ', ' C + + ', ' C # ', ' Perl ', ' VB ', ' HTML ', ' CSS ', ' objective-c ']; 2    function(key, Val) {3        //  firebug console4        console.log (' Index in Arr: ' + key + ', corresponding value: ' + val '; 5        //  If you want to exit loop 6        //  return false; 7    });

One more Test program:

 var  fruit = [' apple ', ' banana ', ' orange ', ' cantaloupe ', ' Mango ' ); // $.each () iterates through an array  $ (' Input#js_eac H '). Click (function   () { $.each (fruit, function   (Key,val) { //  The callback function has two parameters, the first is the element index, the second is the current value  (' Fruit Array, index: ' +key+ ' corresponds to the value: ' +val "); 10 }); 

For: relative to the native. In,each a little stronger. For: In can also iterate through the array and return the corresponding index, but the value needs to be obtained by Arrname[key];

$.grep (Array, callback, [invert]) filter

Filter the array elements using the filter function. This function passes at least two arguments (the third argument is true or FALSE, the return value of the filter function is reversed and the individual is not very useful): array to filter and filter function. The filter function must return true to preserve the element or false to delete the element. In addition, the filter function can also be set as a note string (personal not recommended, to understand the self-access);

1    var temp = []; 2    function(val, key) {3        if(Val.indexof (' C ')! =-1)4            return  true; 5        //  if the [invert] parameter is not given or false, $.grep only collects array elements that return true for the callback function 6        //And  vice versa [ Invert] parameter is true, $.grep collects the callback function to return false array element 7    false); 8    Console.dir (temp);

One more Test program:

01//$.grep () filter Array$ (' Input#js_grep '). Click (function(){$.grep (Fruit,function(val,key) {04//The filter function has two parameters, the first is the current element, the second is an element index05if(val== ' Mango '){Alert (' array value for mango subscript is: ' +key);07            }08        });09 10var_mozigt1=$.grep (Fruit,function(val,key) {11returnKey>1;12        });The element with an index value greater than 1 in the alert (' Fruit ' array is: ' +_MOZIGT1);14 15var_mozilt1=$.grep (Fruit,function(val,key) {16returnKey>1;17},true);18//A Third reliable parameter is passed here, and the return value in the filter function is reversed .Alert (' Fruit ' elements with index values less than or equal to 1 in the array are: ' +_mozilt1);20});
$.map (Array,[callback]) converting an array by a given condition

The conversion function as a parameter is called for each array element, and the conversion function is passed a parameter that represents the transformed element. A conversion function can return a converted value, null (delete an item in an array), or an array containing a value, and extend to the original array. This is a very powerful method, but it is not commonly used. It can update the value of an array element based on a specific condition, or extend a new copy element based on the original value.

01//only arrays are supported for versions prior to 1.6Geneva temp = $.map (arr,function(Val, key) {03//returns NULL, the length of the returned array minus 104if(val = = = ' vb ')return NULL;05returnVal;06    });07Console.dir (temp);08//1.6 Start support for JSON-formatted object09varobj = {key1: ' Val1 ', Key2: ' Val2 ', Key3: ' Val3 '};temp = $.map (obj,function(Val, key) {11returnVal;12    });Console.dir (temp);

One more Test program:

01//$.map () converting an array by a given condition$ (' Input#js_map '). Click (function(){03var_maparra=$.map (Fruit,function(val) {04returnval+ ' [New plus] ';05        });06var_maparrb=$.map (Fruit,function(val) {07returnval== ' Apple '? ' [Add only to Apple] ' +Val:val;08        });09var_maparrc=$.map (Fruit,function(val) {10//expands a new element for an array element11return[Val, (val+ ' [Extended] ')];12        });The array of alert (' add ' after each element ' [New plus]\ ' character) is: ' +_maparra);The array of alert (' Add characters only to the element Apple is: ' +_MAPARRB);Alert (' For each element in the original array, extend an add character \ ' [new add]\ ' element, return an array of ' +_MAPARRC);16});
$.inarray (Val,array) determine if the value exists in the array

Determines the position of the first parameter in the array, counting from 0 (returns-1 if not found). Remember the indexof () method? IndexOf () returns the first occurrence of the string, and $.inarray () returns the position of the passed-in parameter in the array, similarly, if found, returns a value greater than or equal to 0, or 1 if not found. Now, know how to use it. With it, it becomes easy to determine whether a value exists in the array.

1    // Returns the position of the element in the array, 0 is the starting position, and 1 does not find the element 2    console.log ($.inarray (' JavaScript ', arr));

Test procedure:

 // $.inarray determines whether the value is in the array, there is no return-1, exists returns the corresponding index value  "Input#js_inarray". Click (function   () { var  _exist=$.inarray (' Mango ' _exist ');  07  if  (_inexistence< 0 "The durian does not exist in the array fruit!, the return value is: ' +_inexistence+ '! '  10}  one}); 
$.merge (First,second) merging of two arrays

The returned result modifies the contents of the first array-the elements of the first array followed by the elements of the second array. This method replaces the native Concat () method with jquery, but the function is not concat () powerful, and concat () can combine multiple arrays at the same time.

1    var frontEnd = [' JavaScript ', ' CSS ', ' HTML '],2          backend = [' java ', ' php ', ' C + + '); 3    //  This method modifies the first parameter, that is, the frontEnd array 4    temp = $.merge (frontEnd, backend); 5    Console.dir (temp); 6    Console.dir (frontEnd); 7    //  can be used in the following way to avoid the effect on the original array 8    //  $.merge ($.merge ([], frontEnd), backend );

Test program

1    //$.merge () merges two arrays of 2    $ (' Input#js_merge '). Click (function() {3        // native concat () may be more concise than it is 4        fruitnew=$.merge (fruit,[' peach ', ' dragon fruit ', ' watermelon ', ' carambola ', ' lychee ', ' Longan ')5        Alert (' The new array length after merging: ' +fruitnew.length+ '. The value is: ' +fruitnew); 6    });
$.unique (array) filters repeating elements in an array

Deletes the repeating element in the array. Handles only the deletion of an array of DOM elements, not a string or a numeric array. Seeing this method for the first time, I think this is a very convenient way to filter the repetition, ha, how perfect, but a closer look, only the processing of DOM elements. function 80 percent. So, I've defined it as a less common element, at least I haven't used it since jquery.

 <div>blahblahblah....</div>02 <div></div>03 <div class= "DUP" ></div>04    <div class= "DUP" ></div>05 <div class= "DUP" ></div>06 <div></div>07 08 //  $.unique supports only DOM element arrays, removes duplicate DOM elements, and does not support other types of arrays (string or number)  //  Get the original Dom array instead of the jquery encapsulated  var  divs = $ (' div '  "). get ();  One //  add several div with a class of dup  divs = Divs.con Cat ($ (' div.dup ' ). get ());  Console.log ("Before unique:" + divs.length);  DIVs = $.unique (divs);  Console.log ("After unique:" + divs.length); 

Test procedure:

    $.unique () filter the repeating element in the array (only the DOM element array)is    $ (' Input#js_unique '). Click (function () {        var _h2arr=$.makearray (h2obj);         The array _h2arr repeats once        _h2arr=$.merge (_h2arr,_h2arr);        var _curlen=_h2arr.length;        _h2arr=$.unique (_h2arr);        var _newlen=_h2arr.length;        _h2arr alert (' array ' original length value: ' +_curlen+ ', filtered to: ' +_newlen+ '. Total filtering ' + (_curlen-_newlen) + ' repeating element '); (Ten    });
$.makearray (obj) converts class array objects to arrays

Converts a class array object to an array object that has the length property and has a member index of 0 to Length-1. This is a redundant method, the omnipotent $ would have included this feature. The jquery official online explanation is very vague. In fact, it is the conversion of a class array object (such as a collection of element objects obtained with getElementsByTagName) to an object of the tuple.

First, what is a class array object? The jquery website uses divs = Getelementsbytag (' div ') as an example, and this divs has some similar array-like methods such as length, gets the element by [index], and then through $. Makearray (divs) allows it to be transformed into an array, using other functions of the array, such as reverse (), pop (), and so on.

1    //$.makearr () class array conversion 2    $ (' Input#js_makearray '). Click (function() {3        var _makearr=$.makearray (h2obj); 4        alert (the data type of the H2 element object collection is converted to: ' +_makearr.constructor.name); 5    });
$ (DOM). ToArray () Restores all DOM elements to an array

Restores all DOM elements in the jquery collection to an array, not the usual method, and the individual even feels it is as superfluous as $.makearray.

1    //$ (DOM). ToArray () Restores all DOM elements to an array of 2    $ (' Input#js_toarray '). Click (function  () {3        var _toarr=$ (' H2 '). ToArray (); 4        alert (' H2 element collection after the recovery of the data type is: ' +_toarr.constructor.name); 5    });

Some operations summary of jquery array

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.