Jquery array encapsulation USES the method share of jquery array traversal

  • 2020-03-30 02:27:22
  • OfStack

$. Each traversal (array, [callback])

Is different from the case through the jQuery object $. The each () method, this method can be used in cases of any object again oh ~ (not just array). The callback function has two parameters: the first for a member of the object or array index, the second for the corresponding variable or content. If you need to exit the each cycle can make the callback function returns false, the other the return value is ignored.

Each traversal is a variant of the for loop in normal event processing, but it is more powerful than the for loop.

Usage:


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 '];
  // gets the collection of objects of h2 elements using the native getElementsByTagName
  Var h2obj = document. GetElementsByTagName (' h2);

  //$.each() traverses the array
  $(' input# js_each '). Click (function () {
    $. Each (fruit, function (key, val) {
      The // callback function takes two arguments, the first to the element index and the second to the current value
      Alert (in 'fruit array, index: '+key+' corresponds to: '+val);
    });
  });

[/ code]
As opposed to the native for.. In,each is stronger. In can also iterate over groups and return the corresponding index, but the value needs to be obtained through arrName[key].

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

Filter array element filter function is used. This function is to pass at least two parameters (the third parameter to true or false, to take the filter function return values, personal feel useless) : to filter array and filtering function. The filter function must return true to keep elements or false to remove elements. In addition, the filter function can also be set to a note string (personal is not recommended for reference).


v[code]ar temp = [];
temp = $.grep(arr, function(val, key) {
 if(val.indexOf('c') != -1) 
  return true;
 //If the [invert] parameter is not given or false, $.grep collects only the array elements for which the callback returns true
 //Invert is true, and $.grep collects the array elements that return false
}, false);
console.dir(temp);

Another test program:


 //$.grep() filters the array
 $('input#js_grep').click(function(){
  $.grep(fruit,function(val,key){
   //The filter function takes two arguments, the first for the current element and the second for the element index
   if(val==' Mango. '){
    alert(' An array of values for   Mango.   The subscript is : '+key);
   }
  });

  var _moziGt1=$.grep(fruit,function(val,key){
   return key>1;
  });
  alert('fruit The index value in the array is greater than 1 Elements for : '+_moziGt1);

  var _moziLt1=$.grep(fruit,function(val,key){
   return key>1;
  },true);
  //Here a third reliable parameter is passed, inverting the return value in the filter function
  alert('fruit The index value in the array is less than or equal to 1 Elements for : '+_moziLt1);
 });

$.map(array,[callback]) converts the array as given

The conversion function as a parameter will call for each array element, and gives the conversion function transfer a said converted elements as arguments. Conversion functions may return values of the transformed, null (delete) of the array, or an array contains the value, and extended to the original array. This is a very powerful way, but it is not commonly used. It can be according to specific conditions, update the array element value, or a new copy of the elements according to the original value of extension.


//Previous versions of 1.6 supported only arrays
temp = $.map(arr, function(val, key) {
 //Returns null and returns the length of the array minus 1
 if(val === 'vb') return null;
 return val;
});
console.dir(temp);
//1.6 support for json-formatted objects began
var obj = {key1: 'val1', key2: 'val2', key3: 'val3'};
temp = $.map(obj, function(val, key) {
 return val;
});
console.dir(temp);

Another test program:


 //$.map() converts the array as given
 $('input#js_map').click(function(){
  var _mapArrA=$.map(fruit,function(val){
   return val+'[ New added ]';
  });
  var _mapArrB=$.map(fruit,function(val){
   return val==' apple ' ? '[ Only apples ]'+val : val;
  });
  var _mapArrC=$.map(fruit,function(val){
   //Extends a new element for the array element
   return [val,(val+'[ extension ]')];
  });
  alert(' After each element '[ New added ]' The array after the character is : '+ _mapArrA);
  alert(' Only to elements   apple   The array after adding the characters is : '+ _mapArrB);
  alert(' Is each element in the original array , Extends an add character '[ New added ]' The elements of the , 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 count from 0 (-1 if not found). Remember the indexOf() method? IndexOf () returns the string for the first time in the position, and $. InArray () returns the position of the incoming parameters in the array, the same, if found, returns a value greater than or equal to zero, if not found then return 1. Now, know how to use it. With it, to determine whether a value is present in the array, becomes easy.


//Returns the position of the element in the array,0 as the starting position, and -1 as the element is not found
console.log($.inArray('javascript', arr));

 Test procedures: 
[code]
 //$.inarray determines whether the value is in the array, returns -1 if it does not exist, and returns the corresponding index value if it does
 $('input#js_inarray').click(function(){
  var _exist=$.inArray(' Mango. ',fruit);
  var _inexistence=$.inArray(' durian ',fruit)
  if(_exist>=0){
   alert(' Mango.   Exists in array fruit In the , Its index value in the array is : '+_exist);
  }
  if(_inexistence< 0){
   alert(' durian   It doesn't exist in an array fruit In the !, The return value is : '+_inexistence+'!');
  }
 });

Merge (first,second) merges two arrays

The result modifies the contents of the first array -- the elements of the first array are followed by the elements of the second array.


var frontEnd = ['javascript', 'css', 'html'],
   backEnd = ['java', 'php', 'c++'];
//This approach modifies the first parameter, the frontEnd array
temp = $.merge(frontEnd, backEnd);
console.dir(temp);
console.dir(frontEnd);
//You can avoid affecting the original array in the following ways
// $.merge($.merge([], frontEnd), backEnd);

The test program


 //Merge () merges two arrays
 $('input#js_merge').click(function(){
  //Native concat() is probably a little more concise
  fruitNew=$.merge(fruit,[' peach ',' pitaya ',' watermelon ',' carambola ',' litchi ',' longan '])
  alert(' The length of the new array after merging is : '+fruitNew.length+'.  The value of : '+fruitNew);
 });

$.unique(array) filters duplicate elements in an array

Deal only delete the repeating element in the array. Remove DOM element array, and cannot handle string or digital array. The first time see this approach, think this is a very convenient method, can filter repeat, ha, more perfect, but a look at carefully, only working with the DOM elements. 8 fold functional. So, I don't give it a definition has become a common elements, at least, since I use the jQuery useless to it.


<div>blahblahblah....</div>
<div></div>
<div class="dup"></div>
<div class="dup"></div>
<div class="dup"></div>
<div></div>
//$.unique only supports an array of DOM elements and removes duplicate DOM elements. No other types of array (String or Number) are supported.
//Get the original DOM array, not the one encapsulated by jQuery
var divs = $('div').get(); 
//Add several divs with the class dup
divs = divs.concat($('div.dup').get()); 
console.log("before unique:" + divs.length);
divs = $.unique(divs);
console.log("after unique:" + divs.length);

Test procedures:


 //$.unique() filters duplicate elements in the array (DOM element array only)
 $('input#js_unique').click(function(){
  var _h2Arr=$.makeArray(h2obj);
  //Repeat the array _h2Arr
  _h2Arr=$.merge(_h2Arr,_h2Arr);
  var _curLen=_h2Arr.length;
  _h2Arr=$.unique(_h2Arr);
  var _newLen=_h2Arr.length;
  alert(' An array of _h2Arr The original length is zero : '+_curLen+' , The filtered for : '+_newLen+' . A total of filtering  '+(_curLen-_newLen)+' Individual repeating elements ');
 });

$.makearray (obj) converts a class array object to an array

Transform class array object as an array object, class array object has length attribute, its members index of 0 to length - 1. This is a redundant method, omnipotent $already contains the function. The jQuery website to explain very fuzzy. In fact, it is a kind of array object (using getElementsByTagName to obtain element collection of objects, for example) into an array of objects.

What is an array of classes first? JQuery website with divs = getElementsByTag (' div ') as an example, this divs has some array-like methods such as length, through the [index] method to get the elements, etc., and then through $. MakeArray (divs) to make it into an array, you can use other functions of the array, such as reverse (), pop (), etc.


 //$.makearr () class array conversion
 $('input#js_makearray').click(function(){
  var _makeArr=$.makeArray(h2obj);
  alert('h2 The data type of the collection of element objects is converted to : '+_makeArr.constructor.name);
 });

$(dom).toarray () restores all dom elements to an array

Restore all DOM elements in the jQuery collection into an array; A less common method that individuals might find as redundant as $. MakeArray.


 //$(dom).toarray () restores all dom elements to an array
 $('input#js_toarray').click(function(){
  var _toArr=$('h2').toArray();
  alert('h2 The recovered data type of the collection of elements is : '+_toArr.constructor.name);


Related articles: