JavaScript Array Summary

Source: Internet
Author: User
Tags javascript array

An array is an ordered set, and the type of the elements in the JavaScript array can be arbitrary, and the type between the different elements of the same array can be different. An array is also an object, with a length property that records the lengths of the array.

  1. Create an array
    There are two ways of doing this:
    Array direct amount, var arr = [1, 2,]; This creates an array of two elements. This is not a 3 element because the last comma is optional.
    Another way is to call the constructor:
    var arr = new Array (10), which creates an array with 10 elements;
    var arr = new Array (1,2,3,4,5,6); directly into the array element
      
  2. Reading and writing of array elements
    Arrays are special objects, and arrays are special in maintaining a length property. The index of an array is actually the object's property, and the property value of 0--2 ' 32-2 is the index. The index of 0--2 ' 32-2 is automatically converted to the property value of the string. As follows:
    var a = [+];    Console.log (a.[0])//1

    An array is an object, because you can add properties to it:

    var a = [];
    a.test = ' Test ';
    Console.log (a.length);
    a[' 0 '] = 3;
    Console.log (a.length);
    Console.log (a.test);//test
    Console.log (a[' 0 ');//3
    Console.log (a[0])//3

    As you can see from the above, adding the ' 0 ' attribute to the array is also automatically converted to an index.

  3. Array length
    The Length property is always 1 larger than the largest index (non-sparse array). This length property has some special behavior.
    Automatic maintenance When adding an index to an array:
    var a = [1,2,3];    Console.log (a.length); // 3    a[34;    Console.log (a.length); // 4

    When you change a nonnegative integer that is longer than the current length, those elements that are greater than or equal to the length are deleted:

    var a = [1,2,3,4,5,6,7,8,9];    Console.log (a.length); // 9    A.length = 8;    Console.log (a[8]); // undefined    A.length = 7;    Console.log (a[7]); // undefined

    When you change the length to a nonnegative integer that is longer than the current size, it is equivalent to adding a blank area.

  4. Array traversal
    Use for:
     for (var i = 0; i < array.length; i++) {            }

    One problem with this is that you want to access the length property of the array many times, so it's better to do the following:

     for (var i = 0, len = array.length; i < Len; i++) {    }

    Or, like this, we'll start from behind:

     for (var i = array.length-1; I >= 0; i--) {            }

    You can also use for/in to traverse:

     for (var in array) {            }

    But the problem with this is that , in addition to indexed properties, there are inherited attributes, negative integer attributes, and string properties that are included.

    ECMA5 defines a foreach function:

    var a = [1,2,3,4,5];    A.foreach (function(index) {        console.log (index)    })



  5. Array method
    1. Conversion Method ToString (), tolocalstring (), ValueOf (), join ();
      The valueof gets the array itself. The second and third get is an array, which actually invokes the ToString or toLocaleString function on each element.
      var a = [1,2,3,4,5];    Console.log (A.tolocalestring ()); // 1,2,3,4,5    Console.log (A.tostring ()); // 1,2,3,4,5    Console.log (A.valueof ()); //[1,2,3,4,5]

      And it flattens the array:

      var a = [1,2,3,4,5,[6,7,[8,9]];    Console.log (A.tolocalestring ()); // 1,2,3,4,5,6,7,8,9    Console.log (A.tostring ()); // 1,2,3,4,5,6,7,8,9

      The Join method uses the given character to connect an array element to a string. The ToString method is actually called for each element.

    2. var a = [1,2,3,4,5,[6,7,[8,9]]
      Console.log (A.join (' * '));//1*2*3*4*5*6,7,8,9
      Console.log (a);//var a = [1,2,3,4,5,[6,7,[8,9]]

    3. The
    4. stack method push (), pop ()
      Push adds an element after the array and increments the length value.
        var  a = [1,2,3,4,5 //    5  A.push (6 // 6  Console.log (a[a.length-1]); // 6  
      The

      Pop is just the opposite, and it returns the deleted element.

    5. Queue method Shift (), Unshift ()
      Shift deletes and returns the first element of the array, and the subsequent elements move forward, reducing the value of length.
          var a = [1,2,3,4,5];    Console.log (a.length); // 5     a.shift ();    Console.log (a.length); // 4    Console.log (A[0]); // 2

      Unshift just the opposite.

    6. Reorder methods Reverse (), sort ()
      The reverse method is to reverse the array.
          var a = [1,2,3,4,5];    Console.log (A.reverse ()); // [5, 4, 3, 2, 1]    Console.log (a); // [5, 4, 3, 2, 1]

      As you can see, reverse is directly changing the array itself.
      Another sort method accepts a function as the basis for sorting. If this argument is not passed, the ToString method is called on each element and then compared. That is, all converted to strings and then compared.

          var a = [2,43,25,64,62,45,75,10,4,7]    console.log (A.sort ()); // [2, 4, A, 7, ten]    . Console.log (a); // [2, 4 , A, 7, ten].

      If you pass in a function, the function has two parameters, which is two data to compare. such as function (A1,A2) {}; If you want the A1 to be in front, return less than 0; you want to return 0 in the same order; another situation you know. If you want to sort by the number of small to large.

      var a = [2,43,25,64,62,45,75,10,4,7]    console.log (a.sort (function(A, b) {         return A- b;    }); // [2, 4, 7, ten, +,--------]    Console.log (a); // [2, 4, 7, ten, +,--------]
    7. Operating methods Concat (), slice (), splice ()
      Concat is to append an array to another array.
          var a = [1,2,3,4];     var b = [5,6,7,[7,8],9];    Console.log (A.concat (b))//[1, 2, 3, 4, 5, 6, 7, [7,8], 9]    Console.log (a)//[ 1,2,3,4];    Console.log (b)//[5,6,7,[7,8],9]

      you can see that concat does not flatten the array, and it does not change the original array . It wants to create a copy of a, then copy b in and then return.

      Slice is based on the current array, creating a new array. Accepts two parameters, and the second parameter is optional. If there is only one parameter, it is the item from the specified position to the last one. If there are two parameters, it is the item from the first to the second specified position, but not the last one. The second argument can be a negative number, 1 represents the last item, but not the last one.

          var a = [1,2,3,4,5];    Console.log (A.slice (1)); // [2,3,4,5]    Console.log (A.slice (0, 3)); // [A]    Console.log (A.slice (0,-3));; // [up]

      Similarly, slice does not change the original array. And when the position of the second parameter precedes the position of the first parameter, an empty array is returned.

      The splice feature is very powerful and can be removed, inserted, replaced
      If only two parameters are passed, that is, delete, the first parameter represents the location to be deleted, and the second parameter represents the number of items to be deleted.

      var a = [1,2,3,4,5];    Console.log (A.splice); // [2,3]    Console.log (a); // [1,4,5]


      If more than two parameters are passed in, and the second parameter is 0, it is inserted. The first parameter represents the position to be inserted, and the third and subsequent parameters represent the item to be inserted.

          var a = [1,2,3,4,5];    Console.log (A.splice (1,0,7,8)); // []    Console.log (a);   [1,7,8,2,3,4,5]


      If more than two parameters are passed in, and the second parameter is not 0, it is a replacement. The first parameter represents the start position to be replaced, the second parameter represents how many items to replace, and the third and later parameters represent the items to be replaced.

          var a = [1,2,3,4,5];    Console.log (A.splice (1,2,7,8)); // [2,3]    Console.log (a); // [1,7,8,4,5]

      Last look at an example:

          var a = [1,2,3,4,5];    Console.log (A.splice (-1,2,7,8)); // [5]    Console.log (a); // [1, 2, 3, 4, 7, 8]

      This example shows that the first parameter accepts a negative number, and 1 represents the last item.

    8. Location Method IndexOf (), LastIndexOf ()
      The difference between the two methods is one from the go after looking, one from the back forward. Returns the location of the first found item.
      Accepts two parameters, the first is the item to find, and the second is the position to start.
          var a = [1,2,3,4,5,4,3,2,1]    console.log (A.indexof (4));   3    console.log (A.lastindexof (4));   5


    9. iterative Methods foreach (), some (), map (), filter (), every ()
      all accept two parameters, the first is a function to be called, and the second argument is optional if the first function is called as a method of that parameter. The function passed in has three parameters, the array element, the element index, the array itself

      foreach is the function called on each item, there is no return value. and cannot be ended prematurely with a break. The
      map invokes a function on each item, returning an array of function return values. The
      filter invokes a function on each item, returning an array of items that make the function return a value of true. The method skips the empty element. The
      every invokes a function on each item, and returns True if each return value is true. The
      some invokes a function on each item, and returns False if each return value is false.
    10. Merge function reduce (), reduceright ()
      These methods accept two parameters, the first is a function to be called, the second argument is optional, and the initial value of the passed function. The passed-in function has four parameters, the last merge result, the array element, the element index, and the array itself.
      Reduce will call the function from the first item, the function return value is passed as the first argument to the next function call, and so on, until finally, return a last value as the return value.
      var a = [];      for (var i = 1; I <=; i++) {        a[i-1] = i;    }     var resule = A.reduce (function(last, value, I, arr) {        return last + value    })    Console.log (resule)//5050

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.