jquery Array encapsulation use method sharing

Source: Internet
Author: User
Tags array length arrays constructor extend

The

 jquery array processing is very convenient and powerful, and one-step encapsulates a number of functions that are not accessible to native JS arrays. Here's a look at the power of the jquery array.  

$.each (Array, [callback]) traversal   The $.each () method, which is different from the example of a JQuery object, can be used to iterate over any object (not just an array, oh ~). The callback function has two parameters: the first is the index of the member or array of the object, 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, believe is not unfamiliar, in the ordinary event processing, is for the loop variant, but is more powerful than the for loop. In an array, it can easily capture the array index and its corresponding value. Example:   Use the following method:     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 ', ' cantaloupe ', ' Mango '];  //the object Set  var h2obj=document.getelementsbytagname (' H2 ') to obtain the H2 element from the native getElementsByTagName;    //$.each () traversal array  $ (' Input#js_each '). 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    alert (' Fruit Array, index: ' +key+ ' corresponds to the value: ' +val ');  });  });   [/code] relative to native for.. In,each a little stronger. FoR.. In can also traverse the array and return the corresponding index, but the value is to be obtained through Arrname[key];   $.grep (Array, callback, [invert]) filter   Use filter function to filter array elements. This function passes at least two arguments (the third argument is true or false, and the filter function returns a value that is not useful to the individual): Arrays to filter and filter functions. The filter function must return true to preserve the element or false to delete the element. In addition, the filter function can be set to a note string (individuals do not recommend, to understand their own lookup);     Code as follows: V[code]ar temp = []; temp = $.grep (arr, function (val, key) { if (Val.indexof (' C ')!=-1)     return true;  //if the [invert] parameter does not give or false, $.grep only collects the array elements that the callback function returns True  //the [invert] argument to True, $.grep the array element} that collects the callback function false, false); Console.dir (temp);     Another test program:   Code is as follows:  //$.grep () filter array  $ (' Input#js_grep '). Click (function () {  $.grep ( The Fruit,function (val,key) {   //filter function has two parameters, the first is the current element, the second is the element index    if (val== ' mango ') {    alert (' The array value is the mango subscript: ' +key ';    }  });     var _mozigt1=$.grep (fruit,function (val,key) {   return key>1;  });   Alert (the element with index value greater than 1 in the ' Fruit array is: ' +_MOZIGT1);     var _mozilt1=$.grep (Fruit,function (Val,Key) {   return key>1;  },true);  //Here a third reliable parameter is passed, and the return value in the filter function is reversed   alert (the element with index value less than or equal to 1 in the ' Fruit array is: ' +_mozilt1);  });     $.map (Array,[callback]) converts an array by a given condition   a conversion function that is a parameter is invoked for each array element, and the transformation function is passed an element that represents the transformation as an argument. A conversion function can return a converted value, null (delete an item from an array), or an array that contains values, and extend to the original array. This is a very powerful method, but it is not commonly used. It can update an array element value based on a specific condition, or extend a new replica element based on the original value.     Code as follows://1.6 version only supports array temp = $.MAP (arr, function (val, key) { //returns NULL, the returned array length minus 1  if (val = = ' vb ') return null;  return Val; }); Console.dir (temp); 1.6 begins to support JSON-formatted object var obj = {key1: ' Val1 ', Key2: ' Val2 ', Key3: ' Val3 '}; temp = $.map (obj, function (val, key) { return val;}); Console.dir (temp);     Another test program:     Code is as follows:  //$.map () converts the array  $ (' Input#js_map ') to the given condition. Click (function () {  var _maparra=$.map (Fruit,function (val) {   return val+ ' [new addition] ';  } ');   var _maparrb=$.map (Fruit,function (val) {   return val== ' Apple '? ' [Apple plus] ' +val:val;  });   var _maparrc=$.map (Fruit,function (val) {   //expands a new element for an array element    return [Val, (val+ ' [extension]]];  });   Alert (' After each element is appended with the ' [New plus] ' character, the array is: ' + _maparra ');   Alert (' only add characters to element Apple after the array is: ' + _MAPARRB);   Alert (' For each element in the original array, extending an element that adds a character ' [New] ', the returned array is ' +_MAPARRC ');  });     $.inarray (Val,array) determine if the value exists in the array   determines the position of the first argument in the array, counting from 0 (or 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 argument in the array, and, if found, returns a value greater than or equal to 0, or 1 if not found. Now, you know how to use it. With it, it becomes easy to judge whether a value exists in an array. The     code is as follows://Returns the position of the element in the array, 0 is the starting position, and returns-1 does not find the element Console.log ($.inarray (' JavaScript ', arr));     TEST program: [Code]  //$.inarray determines whether the value is in the array, does not exist return-1, and the existence returns the corresponding index value  $ (' Input#js_inarray '). Click (function () {  var _exist=$.inarray (' Mango ', fruit);   var _inexistence=$.inarray (' Durian ', fruit)   if (_exist>=0) {& nbsp  alert (' Mango exists in the array fruit, its index value in the array is: ' +_exist ');  }   if (_inexistence< 0) {   alert (' Durian does not exist in array fruit!), the return value is: ' +_inexistence+ '! ');  }  };       $.merge (first,second) Merge two array   The result of the return 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 functionality is not concat () powerful, and concat () can combine multiple arrays at the same time.   Code as follows: var frontend = [' JavaScript ', ' CSS ', ' html '],    backend = [' java ', ' php ', ' C + + ']; This way modifies the first parameter, the frontend array temp = $.merge (frontend, backend); Console.dir (temp); Console.dir (frontend); You can use the following methods to avoid the effect on the original array//$.merge ($.merge ([], frontend), backend);     test program   code as follows:  //$.merge () merges two arrays  $ (' Input#js_merge '). Click (function () { /native concat ( May be more concise than it   fruitnew=$.merge (fruit,[' peach ', ' dragon fruit ', ' watermelon ', ' carambola ', ' Litchi ', ' Longan '])   alert (' The merged new array length is: ' + Fruitnew.length+ '. The value is: ' +fruitnew ';  });     $.unique (array) filter the repeating elements in the array   Delete the repeating elements in the array. Handles only the deletion of a DOM element array, not a string or a numeric array. The first time to see this method, think this is a very convenient way, you can filter the repetition, ha, how perfect, but a closer look, only limited to processing DOM elements. function 80 percent. So, I've defined it as a less common element, at least, I haven't used it since jquery.     Code as follows: <div>blahblahblah....</div> <div></div> <div class= "dup" ></div> <div class= "dup" ></div> <div class= "DUP" ></ Div> <div></div>//$.unique supports only DOM element arrays, eliminates duplicate DOM elements, does not support other types of arrays (string or number)///Gets the original Dom array, Instead of jquery-encapsulated var divs = $ (' div '). Get (); //Add a few class-dup div divs = divs.concat ($ (' div.dup '). Get ());  console . log ("before unique:" + divs.length); DIVs = $.unique (divs); Console.log ("After unique:" + divs.length);     test program:     Code is as follows:  //$.unique () filters repeating elements in an 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+ ', Filtered by: ' +_newlen+ '. Filter ' + (_curlen-_newlen) + ' repeating element ');  });     $.makearray (obj) converts class array objects to arrays   Converts an array object of a class to an array object with a length property and a member index of 0 through length-1. This is a redundant method, omnipotent $ This feature is already included. JQUery's explanation on the internet is very vague. Instead, it converts an array object of a class, such as a collection of element objects obtained with getElementsByTagName, to an arrays of objects.   First what is a class array object? The jquery official web site uses divs = Getelementsbytag (' div ') as an example, and this divs has some sort of array-like length, gets the element through [index], and then passes $. Makearray (divs) makes it an array and can use other functions of the array, such as reverse (), pop (), and so on.     Code as follows:  //$.makearr () class array conversion  $ (' Input#js_makearray '). Click (function () {  var _makearr=$. Makearray (H2obj);   Alert (the data type of the ' H2 element object collection is converted to: ' +_makearr.constructor.name ');  });     $ (DOM). ToArray () Restores all DOM elements to a group   restores all DOM elements in the jquery collection to an array; it is not commonly used, and the individual even feels that it is as superfluous as $.makearray.     Code as follows:  //$ (DOM). ToArray () Restores all DOM elements to an array of  $ (' Input#js_toarray '). Click (function () {  var _ toarr=$ (' H2 '). ToArray ();   Alert (the data type after the ' H2 element collection 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.