jquery Array Encapsulation use method sharing (jquery array traversal) _jquery

Source: Internet
Author: User
Tags array length

$.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 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, believed to be new, is a variant of the For loop in the usual event processing, but is more powerful than the for loop. In an array, it can easily take the array index and its corresponding value. Example:

Use the following methods:

Copy Code code 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;
});

One more Test program:
[/code]
var fruit = [' apple ', ' banana ', ' orange ', ' cantaloupe ', ' Mango '];
Gets the collection of objects H2 elements with native getElementsByTagName
var h2obj=document.getelementsbytagname (' H2 ');

$.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, and the second is the current value
Alert (' Fruit array, index: ' +key+ ' corresponds to the value: ' +val ');
});
});

[/code]
In relation to the 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

Filter the elements of an array using a filter function. 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): an array to filter and a filter function. 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);

Copy Code code as follows:

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 that return true for the callback function
If the [invert] argument is true, the array element that collects the callback function returns false $.grep
}, False);
Console.dir (temp);

One more Test program:

Copy Code code as follows:

$.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 (' array value for Mango's subscript is: ' +key ');
}
});

var _mozigt1=$.grep (fruit,function (Val,key) {
Return key>1;
});
The element with an index value greater than 1 in alert (' Fruit array is: ' +_MOZIGT1);

var _mozilt1=$.grep (fruit,function (Val,key) {
Return key>1;
},true);
The third reliable parameter is passed here, and the return value in the filter function is reversed
Alert (' Fruit an element with index value less than or equal to 1 is: ' +_MOZILT1 ');
});

$.map (Array,[callback]) converts an array by a given condition

The conversion function as a parameter is invoked for each array element, and the transformation function is passed a parameter that represents the converted element. 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.

Copy Code code as follows:

Versions prior to 1.6 only support arrays
temp = $.map (arr, function (val, key) {
Returns NULL, the array length returned is minus 1
if (val = = ' vb ') return null;
return Val;
});
Console.dir (temp);
1.6 Starting to support JSON-formatted object
var obj = {key1: ' Val1 ', Key2: ' Val2 ', Key3: ' Val3 '};
temp = $.map (obj, function (val, key) {
return Val;
});
Console.dir (temp);

One more Test program:

Copy Code code as follows:

$.map () convert array by given criteria
$ (' Input#js_map '). 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) {
To extend a new element to an array element
return [Val, (val+ ' [extended]]];
});
Alert (' After each element is appended \ ' [New]\ '] The array is: ' + _maparra ');
Alert (' Add characters to element Apple after the array is: ' + _MAPARRB);
Alert (' For each element in the original array, extends an element that adds a character \ ' [New]\ '], the returned array is ' +_MAPARRC ');
});

$.inarray (Val,array) determines whether 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.

Copy Code code as follows:

Returns the position of the element in the array, 0 is the starting position, and return-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) {
Alert (' Mango exists in array fruit, its index value in array is: ' +_exist ');
}
if (_inexistence< 0) {
Alert (' Durian does not exist in the array fruit!, the return value is: ' +_inexistence+ '! ');
}
});

$.merge (First,second) merges 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 functionality is not concat () powerful, and concat () can combine multiple arrays at the same time.

Copy Code code as follows:

var frontend = [' JavaScript ', ' CSS ', ' html '],
backend = [' java ', ' php ', ' C + + '];
This way modifies the first argument, 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

Copy Code code as follows:

$.merge () Merge two arrays
$ (' Input#js_merge '). Click (function () {
Native concat () may be simpler than that.
Fruitnew=$.merge (fruit,[' peach ', ' dragon fruit ', ' watermelon ', ' carambola ', ' Litchi ', ' Longan '])
Alert (' The new array length after merging is: ' +fruitnew.length+ '. Its value is: ' +fruitnew ');
});

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

Deletes a repeating element in an 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.

Copy Code 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, and does not support other types of arrays (string or number)
Get the original Dom array, not the jquery encapsulated
var divs = $ (' div '). get ();
Add a few class div for DUP
DIVs = Divs.concat ($ (' div.dup '). get ());
Console.log ("before unique:" + divs.length);
DIVs = $.unique (divs);
Console.log ("After unique:" + divs.length);

Test program:

Copy Code code as follows:

$.unique () filters repeating elements in an array (DOM element array only)
$ (' Input#js_unique '). Click (function () {
var _h2arr=$.makearray (h2obj);
Repeat the array _h2arr once
_h2arr=$.merge (_h2arr,_h2arr);
var _curlen=_h2arr.length;
_h2arr=$.unique (_h2arr);
var _newlen=_h2arr.length;
Alert (' array _h2arr the original length value: ' +_curlen+ ', Filtered by: ' +_newlen+ '. Filter ' + (_curlen-_newlen) + ' repeating element ');
});

$.makearray (obj) converts class array objects to arrays

Converts a class array object to an array object that has a length property with a member index of 0 to Length-1. This is a redundant method, and an omnipotent $ would contain this functionality. The jquery official online explanation 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.

Copy Code 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 an array

Restores all the DOM elements in the jquery collection to an array; A method that is not commonly used, which the individual even feels is as superfluous as $.makearray.

Copy Code code as follows:

$ (DOM). ToArray () Restores all DOM elements to an array
$ (' Input#js_toarray '). Click (function () {
var _toarr=$ (' H2 '). ToArray ();
The data type of alert (' H2 element collection restored is: ' +_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.