Common Array Methods

Source: Internet
Author: User
Tags array sort object object

When asked about the array method yesterday, asked if the sort () method would change the original array. Originally I guess is not, also say, immediately I think, knowledge this thing, uncertain when directly said unsure or do not know, just by relying on uncertain guess or memory, harm oneself, so I answer do not know. The result is ... I remember the wrong 0.0 or my own summary of the test is more reliable, the impression is more profound. Welcome to make relevant comments or suggestions, thank you in advance ha ~

I. Native JS Method 1. Iterate through the array in (also the method of the object traversal property)
var a = [1, 2, 3];for (x in a) {    console.log (x);}

2. Merging Arrays Concat
var a = [1, 2, 3],    b = [4, 5, 6],    c;c = B.concat (a);     Add a to B, return a new array, and A and B do not change. Unlimited number of parameters Console.log (b); Console.log (c);

3. The value of the merged array is a string join
var a = [1, 2, 3],    B = a.join (' * ');//default is Plus,          console.log (a);      A does not change Console.log (b);

The parameter is the delimiter, the default is "," separates, when the parameter is "the direct connection, commonly used in JS splicing html, such as the custom pop-up window, JS generates the form form."

4. Sorting the array sort
var a = [6, 2, 3, ' a ', ' X ', +],    B = a.sort ();          ASC table Order, first of all, so 20 rows in front of 3 console.log (a);            A changed console.log (b); A.push (' K '); Console.log (b)            ; A and B point to the same object, B equals the alias of a

You can write collation functions in parameters such as all numbers from small to large (note the return value plus or minus)

var a = [3, 2, 6,],    b = a.sort (function (x, y) {        return x-y;    }); Console.log (b);

When not all the numbers, there will be wonderful errors (NaN), see

  

It is important to note the proper use of operators. For Nan, less action is needed, after all it is the only type that is not equal to any value in JS (not a number), including itself (can be used to determine whether a variable is Nan, uninitialized variable is untyped).

5. Array of analog stacks (FILO) and queue (FIFO) methods (both change the original array)
var a = [6, 2, 3, ' a ', ' X ', ' +],    b = a.push (' ab '),    //Add the element at the end, and return the new length    C = A.pop (),         //delete and return the last element of the array    d = a . Unshift (' xy '),//add element at the beginning and return the new length    e = A.shift ();       Delete and return the first element of the array console.log (a); Console.log (b); Console.log (c); Console.log (d); Console.log (e);

It can be seen that such methods add elements to return the added length, and delete the element to return the deleted poor fellow (with splice).

6. Array reverse order Reverse
var a = [6, 2, 3, ' a ', ' X ', +],    B = a.reverse ();       Returns a reference to Console.log (a); Console.log (b);

  

7. Take the desired part of the array slice
var a = [6, 2, 3, ' a ', ' X ', +],    b = A.slice (0, 2);    The subscript is taken from 0 to 2 (excluding 2), and no second parameter defaults to the end. The first parameter is a negative representation of the number starting at the end. The first parameter is less than the second argument is empty. Console.log (a); Console.log (b);           B is a copy of part A, and a does not change itself.

8. Modify the array splice (since the array is modified, the array itself will change)
var a = [1, 2, 3, 4],    B = A.splice (0, 2, 6); Console.log (a);          Console.log (b);          B is the part of the array that was deleted

A.splice (index, NUM, newItem1, newItem2 ...): index is the subscript for the element that starts the selection, NUM is the number of elements to be deleted next, and NewItem is the new element (not required) to be added next (where it was deleted). This method uses the most, such as

Deletes the specified subscript (2, which is the third) element, does not set the NewItem to be added, and num is set to 1

var a = [1, 2, 3, 4],    

Add any number of elements at any location (e.g. add two elements ' 7 ', ' 8 ') at the time of Subscript 2, and Num is set to 0

var a = [1, 2, 3, 4],    B = A.splice (2, 0, 7,8); Console.log (a); Console.log (b);   No Delete, B returns []

Delete elements based on element values (combined with jquery)

var a=[1,2,3,4];a.splice ($.inarray (2,a), 1); Console.log (a);

Plus: Arrays are also special objects (but have their own methods, typically accessed with subscripts), so there are also common methods for objects ToString and valueof
var a = [1, 2, [3,2], 4],    B = a.tostring ();//Convert to a string (no matter how many layers) console.log (a);       
var a = [1, 2, 4],    B = a.valueof ();  Returns the original value (in fact, it's itself ...). ) Console.log (a);       

Summary: In summary, JS array of native methods inside

Modified by: Splice, pop, push, shift, unshift, sort, reverse

Do not modify your body: Slice, concat, join

Two. jquery Common JS Method 1. Traversal

All elements can be manipulated. If you want to satisfy the conditional exit, use return False (most jquery methods can exit this way).

$.each (arr, Callback (Key, Val)); Can be chained call, return arr, for itself

var a = [1, 2, 3, 4];$.each (A, function (key, Val) {     //} with jquery object method call, compatibility is good; You can also convert a to jquery object with $ (a), and then $ (a). each ( function () {}) is called in the form of the following method with    Console.log (A[key] + ' subscript ' + key + ' value ' + Val ');
Corresponding source code (jquery1.11.0 below the same)

//Execute a callback for every element in the matched set.
//(You can seed the arguments with a array of args, but this is
//only used internally.

Each:function (obj, callback, args) {var value, i = 0, length = obj.length, IsA        Rray = Isarraylike (obj); if (args) {if (IsArray) {for (; i < length; i++) {value = Callbac   K.apply (obj[i], args);                    The third parameter is used to extend the method of the obj element, generally without the if (value = = = False) {break;  }}}} else {for (i in obj) {value = callback.apply (obj[i                    ], args);                    if (value = = = False) {break;            }}}//A special, fast, case for the most common use of each} else { if (IsArray) {for (; i < length; i++) {value = Callback.call (obj[i], I, obj                    [i]);                    if (value = = = False) {break; }               }} else {for (i in obj) {value = Callback.call (obj[i],                    I, obj[i]);                    if (value = = = False) {break;    }}}} return obj; }

 

2. Filtering

$.grep (arr, callback, invert)

 A invert of false indicates that the filter for the callback is reversed. The default is true.

var a = [1, 2, 3, 4];$.grep (A, function (Val, key) {  ///cannot be chained, return [], so you can add return to implement the chain, return the copy that satisfies the condition if (A[key] > 2) {  Console.log (key); } return Val;});

Commonly used to get the same (or not the same) portion of two arrays

var a= [1, 2, 3, 4],    b=[1,3,5,7];$.grep (a,function (val,key) {    if (B.indexof (val) >=0) {        return val;    }} , false);
jquery source Grep:function (Elems, callback, invert) {        var callbackinverse,            matches = [],            i = 0,            length = E Lems.length,            callbackexpect =!invert;        Go through the array, only saving the items        //So pass the validator function for        (; i < length; i++) { C8/>callbackinverse =!callback (elems[i], i);   If callback does not set return, then return undefined (!undefined or undefined) if            (Callbackinverse!== callbackexpect) {                Matches.push (elems[i]);          Add only the internal implementation that satisfies the criteria to the push method            }        }        return matches;    }

  3. Conversion

$.map (Arr,callback (Key,val))

var a = [1, 2, 3, 4];$.map (A, function (Val, key) {//cannot be chained, return [], with grep plus return to put back the copy    if (A[key] > 2) {        a[key]=v al+1;    }    return Val;              Can be chained, return the processed array (can also be used for filtering)});
ARG is for internal usage only    map:function (Elems, Callback, Arg) {        var value,            i = 0,            length = Elems . length,            IsArray = Isarraylike (elems),            ret = [];        Go through the array, translating each of the items to their new values        if (IsArray) {for            (; i < length; i++) {                value = callback (elems[i], I, ARG);                if (value = null) {                    Ret.push (value);                }            }        Go through every key on the object,        } else {            to (I in Elems) {                value = callback (elems[i], I, ARG) ;   If callback does not return a value, then value is undefined                if (value! = null) {                    Ret.push (value);        }}} Flatten any nested arrays        return concat.apply ([], ret);                   If callback has no return value, then value is []
}

The area in which the background is marked is different from the each method, which can be simply understood as whether the return object is a copy (map is a copy), and the map is made for arrays or class array objects, and each can be applied to all objects.

4. Merging

$.merge (ARR1,ARR2) arr1 back arr1 after adding arr2

var a=[1,2,3],    B=[4,5,6];$.merge (A, b);             can have multiple parameters (incredibly no error!), but the third and later useless (test in FF and Chrome)
jquery Source Merge:function (first, second) {        var len = +second.length,             j = 0,            i = first.length;        while (J < len) {            first[i++] = second[j + +];        }        Support:ie<9        //Workaround casting of length to NaN on otherwise arraylike objects (e.g., nodelists)        if (Len!== len) {            while (Second[j]!== undefined) {                first[i++] = second[j + +];}        }        First.length = i;        return first;    }

The second line of the source code has a +, at first I thought it was explicitly declared non-negative, and later saw the Arraylike, and then tested the extreme situation as follows:

var ax;ax.length        //error, type Error+ax.length       //error, type Errorvar ab={};       Empty object as a class empty array object ab.length        //undefined+ab.length       //nanvar ab=[];ab.length        //0+ab.length       //0var ab= Null;ab.length//error, type Error+ab.length       //error, type error

Suddenly feel the egg ... Well, maybe I care too much. If anyone sees the explanation, trouble leaves a word, thank you ~

5. Filter the same elements

$.unique (arr)//filter repeating elements in the jquery object array (internally implemented as = = =) (different versions, do not use)

var a = [1, 1, 2, 3, 7, 4, 5, 5, 6, 6];$.unique (a)

jquery1.11.0 Running Results

jquery1.8.3 Running Results

It's so magical, there's wood! Check out the source insurance ~

Jquery1.11.0jquery.unique = Sizzle.uniquesort; Sizzle.uniquesort = function (results) {    var elem,        duplicates = [],        j = 0,        i = 0;    Unless we *know* we can detect duplicates, assume their presence    hasduplicate =!support.detectduplicates;    Sortinput =!support.sortstable && results.slice (0);    Results.sort (SortOrder);    if (hasduplicate) {while        ((Elem = results[i++])) {            if (elem = = = results[I]) {          //with = = =                J = dupl Icates.push (i);            }        }        while (j--) {            results.splice (duplicates[j], 1);   Implemented with Splice        }    }    //Clear input after sorting to release objects    //See https://github.com/jquery/ sizzle/pull/225    sortinput = null;    return results;};
Jquery1.8.3jquery.unique = Sizzle.uniquesort; Sizzle.uniquesort = function (results) {    var elem,        duplicates = [],        i = 1,        j = 0;    Hasduplicate = basehasduplicate;    Results.sort (SortOrder);    if (hasduplicate) {for        (; (Elem = results[i]); i++) {            if (elem = = = results[I-1]) {                j = duplicates.push (i);}        }        while (j--) {            results.splice (duplicates[j], 1);        }    }    return results;};

corresponding to the red font for new or modified, however, and do not see what, debugging to enter, you will find the problem actually on the SortOrder! Hang on!

View Code in jquery1.11.0View Code in jquery 1.8.3

A lot, isn't it? Have the wood to feel the moment is I pit? Aha, in fact, as long as you continue to debug breakpoints set, you will find that ~ ~ ~ No more than this pit! They're all loops! 1.8.3 inside in the first function inside the rotation, the hands are sour and did not see out, 1.11.0 the whole cycle, there are the number of parameters so many times.

The final conclusion is: Do not use this dubious function. If you need a similar function, write it manually with native JS. At the same time, the importance of attention to update, but the program apes do not necessarily have so long to pay attention to each update, then must be accurate understanding of their own version, it is best to use the function of the free test, look at the source, the net to get the final feeling shallow ah ~

6. Judging

$.inarray (Val,arr) to determine if Val is inside arr

var a = [1, 2, 3, 4];$.inarray (2, a);     Some words return subscript, no words return-1
corresponding source        inarray:function (Elem, arr, i) {            var len;            if (arr) {                if (indexOf) {                    return Indexof.call (arr, elem, i);     Actual implementation                }                len = arr.length;                i = I? I < 0? Math.max (0, Len + i): i:0;                for (; i < Len; i++) {                    //Skip accessing in sparse arrays                    if (i in arr && arr[i] = = = Elem) {     //A As far as possible to use = = = To eliminate the possible implicit conversion                        return i;            }} return-1;        }

 

7. Element to Array

$.makearray () Converts a class array object to a true array object. (The so-called "class Array Object" is a regular object object, but it is very similar to a group object: With the Length property, and with 0, 1, 2, 3 ... Equal number as the property name. However, it is not an array after all, there is no built-in method inherited from the array's prototype object (for example: push (), sort (), and so on). )

$.toarray () Restores all DOM elements to an array. (In fact, the selector is a natural form of the array)
These two actually use too little is not specific analysis, know that this thing is OK.

Three. Add 1. Empty array

Method 1:length is set to 0 (JS is one embodiment of the weakly variable type language, the length property of the array can be written) (less efficient)

Method 2: A reference directly to [] (such as a closure destruction that points to null, garbage collection automatically reclaims space) (high efficiency)

2. Compatibility   

IE8 under
$.inarray instead of IndexOf
$.grep instead of Array.prototype.filter

3. Precautions

In general, it is better to invoke the JQuery method in the form of $.functionname (Obj,callback), such as I have encountered IE8 and the following do not recognize the $ (DOM). Val () Trim (), display trim is not a function, however instead of $.trim ($ (DOM). Val ()) There is no problem.

The previous case is actually a string call to trim method (if you add either the invoke or apply injection trim method can be too, but necessary?) ), followed by a jquery object that calls the Trim method.

Finally, a word, welcome comments and suggestions, help me correct, common progress, thank you!

Tags: js array operation, jquery array operation, array

Common Array Methods

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.