Javascript Array Summary

Source: Internet
Author: User
Tags javascript array

Sparse array
var a1 = [,,,]; var New Array (3); var a3 = [1, 2, 3];console.log ( in A1); // false  in A2); // false  in A3); // true Delete a3[0];console.log ( in A3); // false
Increase or decrease of array elements

Length is set less than the original value, delete overflow, add an array element, length is always the element ordinal +1.

Push/pop operations at the end of an array, as with A[a.length], and can support multiple parameters.

Unshift/shift operation on Array head

Array traversal
if (!a (i)) // null/undefined/elements that do not exist if (A (i) = = = undefined) if  in a)// non-existent element

You can work with a sparse array for in, but this is not recommended for arrays, such as the ability to enumerate inherited property names.

Array of checksum classes for arrays
function (o) {    returntypeof O = = = = =    = "Object" && = = = "[Object Array]";}

Class Array object: Can be traversed by code that is used for real array traversal;

function isarraylike (o) {    if (o &&        typeof o = = = ' Object        ' &&! = 3 &&        &&        >= 0 &&        = = Math.floor (o.length) &&        < 4294967296)        returntrue;     Else        return false ;}
The string as an array

In ES5 (including IE8), the string behaves like a read-only group. In addition to accessing individual characters with Charat, you can also use square brackets. The general method of an array can be used on a string. For example:

s = "JavaScript""")    //  = "J a V a S C R I p T"Array.prototype.filter.call (S,  / /  filter characters in string    function  (x) {        return//  match non-vowel letters only     }). Join ("");    //   = "Jvscrpt"

Note that the string is read-only and will be an error if you use the method that modifies the call array. For example: Push (), sort (), reverse (), splice () array methods.

Methods supported by arrays in ES3

Concat ()-Result return, sort (), reverse (), join ()-result return, slice ()-Result return, splice (), push (), pop (), Unshift (), Shift (), toString (), toLocaleString ()

Concat: Returns a newly created array element that contains the elements of the original array that called concat and each of the concat parameters, if any of these parameters are itself an array, then the elements of the connected array, not the array itself. Note, however, that concat does not recursively flatten an array of arrays, nor does it modify the array of calls.

Array Slice and Splice methods

Slice does not change the original array, and intercepts the original array fragments back. The index starts at 0, when the parameter is positive, the first parameter is not the array of the second argument (from zero, relative to the index), and the inverse of the first argument and the second-to-last argument when the parameter is negative.

Splice change the original array. The first parameter (from zero), the starting position of the insertion or deletion, the second parameter: the number of elements to delete, the third or any other parameter, the element to insert.

Deletes an array element, keeping the array contiguous, using splice, to return an array of deleted elements. When copying an array, use Array.slice.

var len = items.length,    = [],    i; //  Bad  for (i = 0; i < len; i++) {    = items[i];} // gooditemscopy = Items.slice ();
Methods supported by arrays in ES5

ForEach (), map (), filter (), every () and some (), reduce (), and Reducerigth (), IndexOf (), and LastIndexOf ().

ForEach ()

var data = [1, 2, 3, 4, 5];d ata.foreach (function  (v, I, a) {    = v + 1  ;})

You cannot use break to jump out of a loop, like a for, to throw a Foreach.break exception in a function of a foreach () pass-through argument.

 function foreach (A, F, t) {//  A is an array, F is a function, and t is the execution environment of functional F    try  {        A.foreach (f , t);     Catch (e) {        if (e = = = foreach.  break)            return;         Else            Throw e;    }} foreach.  Break New Error ("Stopiteration");

The ES3 does not support foreach () to introduce the following methods

function (FN, context) {    for(var. length >>> 0; i < len; i++ ) {        /c6>ifin this) {            this);}}    );

Map ()

A = [1, 2, 3= A.map (function  (x) {    return x * x;});

The arguments passed are the same as foreach (), unlike the function called by map () to have a return value. The function returns the newly created array without modifying the called array.

Array.prototype.map = Array.prototype.map | |function(callback, Thisarg) {varT, A, K; if( This==NULL) {        Throw NewTypeError ("This is a null or not defined"); }    //1. Assign o to the array that calls the map method.    varO = Object ( This); //2. Assign Len to the length of the array O.    varLen = o.length >>> 0; //4. If callback is not a function, the TypeError exception is thrown.    if({}.tostring.call (callback)! = "[Object Function]") {        Throw NewTypeError (callback + "is not a function"); }    //5. If the parameter thisarg has a value, the T is assigned to THISARG; otherwise t is undefined.    if(thisarg) {T=Thisarg; }    //6. Create a new array A, length is the original array o length lenA =NewArray (len); //7. Assign a value of K to 0K = 0; //8. When K < Len executes the loop.     while(K <Len) {        varKvalue, Mappedvalue; //Traverse O,k as the original array index        if(kinchO) {//Kvalue the value corresponding to the index K.Kvalue =O[k]; //the execution callback,this points to T, with three parameters. Kvalue: value, K: Index, O: the original array.Mappedvalue =Callback.call (T, Kvalue, K, O); //The return value is added to the new book Group A.A[K] =Mappedvalue; }        //k self-increment 1k++; }    //9. Return the new array a    returnA;};

Every () and some ()

The array is logically determined, returns TRUE or false, and note that every () and some () determine what value to return and they stop traversing the element.

Reduce () and reduceright ()

Uses the specified function to combine array elements to produce a single value. This is a common operation in functional programming, called "Injection" and "folding". Reduce requires two parameters, the first parameter is the function that performs the simplification, the parameters of the function are as follows: The result or initialization value, the array element, the index of the element, and the array itself; the second argument (optional) is the initial value passed to the function.

 var  a = [1, 2, 3, 4, 5 var  sum = a.reduce (function   (x, y) { return  x + Y;},  0); var  Product = a.reduce (function   (x, y) { return  x * Y;},  1); var  max = a.reduce (function   (x, y) { return  x > y?  x:y;});  

Reduceright () works the same way as reduce (), where it processes arrays from high to low (right-to-left) by array index.

IndexOf () and LastIndexOf ()

The first parameter represents the element to be searched, and the second element represents the starting position of the search. Can be a negative number, which represents the offset from the end of the array, 1 specifies the last element of the array.

varA = [0, 1, 2, 1, 0];a.indexof (1);//= = 1:a[1] is 1A.lastindexof (1)//= = 3:a[3] is 1A.indexof (3)//=>-1: No element with a value of 3functionFindAll (A, x) {varresult =[], Len=A.length, POS= 0;  while(Pos <Len) {POS=a.indexof (x, POS); if(pos = = =-1) {             Break;        } result.push (POS); POS++; }}

The string also has the indexof () and LastIndexOf () methods.

Javascript Array Summary

Related Article

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.