The use and source analysis of jquery static method Inarray,grep,merge,makearray method

Source: Internet
Author: User

Inarray method

Determines the position of the first parameter in the array, counting from 0 (returns-1 if not found).

Example:

var arr = [4, "Pete", 8, "John" ];jquery.inarray ("John", arr);  // 3 Jquery.inarray (4, arr);  // 0 Jquery.inarray ("David", arr);  // -1 Jquery.inarray ("Pete", arr, 2);  // -1

SOURCE Analysis:

InArray:function(Elem, array, i) {varLen; if(array) {if(indexOf) {returnIndexof.call (Array, elem, i); } Len=Array.Length; I= I? I < 0? Math.max (0, Len + i): i:0;  for(; i < Len; i++ ) {                //Skip accessing in sparse arrays                if(IinchArray && array[i] = = =elem) {                    returni; }            }        }        return-1; },

Accepts 3 parameters, the Elem parameter is the element to find, array is the object to be looked up for the specified position, the default is 0 to find the entire array like the Trim method, ECMA5 also provides a prototype method indexof for the array objects, If the browser that executes the code supports this method to call directly;

  var arr=[1,2,3];       Alert (Arr.indexof (2));  // 1        alert (arr.indexof (2,2));  // -1

For developers who do not need to consider the low version of the browser can be used directly, for unsupported browsers using for...in loop filtering;

First, the length of the array is preserved, according to the length of I to deal with, if I do not exist so that it is 0 if less than 0 plus Len to judge again, if it is less than 0 again to make it 0;

The for...in loop here is not the same as what we normally use, as noted in the note to circumvent sparse arrays, and what is sparse arrays are examples of:

 varArr=[undefined,undefined]; arr[2]=4; Console.log (arr);//[undefined,undefined,4] vari=0;len=arr.length; for(Iincharr) {Alert (iinchARR);//true x 3 } varArr=[]; arr[2]=4; Console.log (arr);//[2:4] vari=0;len=arr.length; for(Iincharr) {Alert (iinchARR);//false x 3 True}

Two arrays use the same method, although the length is 3, the performance value is the same, but the results returned using the in operation is not the same, the second is a sparse array, the element is discontinuous, the for...in loop is automatically added two undfined but the result is false, For this type of array is not required to add JS background undefined, so jquery used this way to deal with, this way is also worthy of reference. Returns the corresponding I value after it is found otherwise returns-1, so it is possible to judge whether the returned result is >-1.

grep method

Filter the array elements using the filter function.

This function passes at least two parameters: the array to be filtered and the filter function. The filter function must return true to preserve the element or false to delete the element.

Example:

function (n,i) {  return n > 0;}); // Results: [1, 2] // exclude elements greater than 0 in the array, and use the third parameter to exclude them.  $.grep ([function(n,i) {  return n > 0True ); // Results: [0]

SOURCE Analysis:

Grep:function(Elems, callback, inv) {varRET =[], RetVal; INV= !!INV; //Go through the array, only saving the items    //That pass the validator function     for(vari = 0, length = elems.length; i < length; i++) {RetVal= !!callback (elems[i], i); if(Inv!==retVal)         {Ret.push (elems[i]); }   }   returnret;
}

The method accepts 3 parameters, Elems is the array to be filtered, callback is the callback function, and inv indicates whether reverse filtering is false by default;

First, the inv is forced to a Boolean value, and then use the For loop, the elements inside the array into the callback function to run, return the result assigned to retval, if retval constant equals inv, put the element into the new array ret, and finally return to RET, It is important to note that the return value of the callback function must be a Boolean value because it is identical.

Merge method

Merging 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.

Example:

// merges two arrays onto the first array. $.merge ([0,1,2], [2,3,4])// Result:[0,1,2,2,3,4]

SOURCE Analysis:

Mergefunction(first, second) {vari =First.length, J= 0; if(typeofSecond.length = = = "Number" ) {          for(varL = second.length; J < L; J + +) {first[i++ ] =second[J]; }    } Else {           while(Second[j]!==undefined) {first[I+ +] = second[J + + ]; }} first.length=i; returnFirst ;},

The method knot accepts two array parameters, the second is the merged array, and the first one is the array to be merged. In fact, the array here is not necessarily a "pure array", there may be an array of classes or objects with a number subscript, and so on;

First, based on the length property of the second array, if the number type is assumed to be an array, it is added to the first array by a for loop. If it is not number or does not exist, then a while loop is used to add or overwrite the value of the second array, not undefined, to the first array corresponding to the subscript value.

Finally, manually fix the length value because the length value is not automatically modified for data that is not a "pure array".

Makearray method

Converts an array of classes object to a group object.

The class array object has the Length property and its member index is 0 to length-1. In practice, this function is automatically used in JQuery without the need for intentional conversion.

Example:

// HTML Code:<div>first</div><div>second</div><div>third</div><div >Fourth</div>//jQuery code:var arr = Jquery.makearray ( document.getElementsByTagName ("div"/ / Use array rollover function // Result:[Fourth,third , Second,first]

SOURCE Analysis:

//results is for internal usage onlyMakearray:function(array, results) {varret = Results | | []; if(Array! =NULL ) {        //the window, strings (and functions) also has ' length '        //tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930        varType =Jquery.type (array); if(Array.Length = =NULL|| Type = = = "string" | | Type = = = "Function" | | Type = = = "RegExp" | |Jquery.iswindow (Array))        {Push.call (ret, array); } Else{jquery.merge (ret, array); }   }   returnret;
},

This takes two parameters, where the second parameter is used internally, and is often called inside the source code as a support method for other methods.

Create a new array ret, if there is only one argument is empty, if there is a second argument to the second parameter to the RET, in the case of the existence of the array parameter to obtain its data type, if the data type is a string, function or regular, or does not have the length property, It is assumed that array is not an array or an array of classes, because strings, functions, and regular (under the BlackBerry System) all have the length property, so only the length is not accurate, if not an array or an array of classes directly put the first argument to the end of a ret. If passed, it is considered an array or an array of classes, at which point the merge method is called to merge the two arrays, and finally returns a Ret.

The use and source analysis of jquery static method Inarray,grep,merge,makearray method

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.