Arrays in JavaScript

Source: Internet
Author: User
Tags array length
JavaScript is a weakly typed language, and arrays in JavaScript are very different from strongly typed languages, such as arrays in Java. Arrays in JavaScript are untyped; array elements can be of any type. JavaScript arrays are dynamic and grow or shrink as needed, and you do not need to redistribute space to create an array without declaring a fixed size or changing the size of the array. JavaScript arrays may be sparse; The index of an array element is not necessarily contiguous, and there may be a vacancy between them. Each array has a length property. For a non-sparse group, this property is the number of array elements. For sparse arrays, length is larger than the index of all elements.
/* Create an array:/

//1. Using the array direct amount,
var empty=[];//an array of Var primes=[2,3,1 with no elements
, and "W"];//an array of four elements

//2. Using the array () constructor
var a=new array ();//array with no elements
var b=new array (10);//called with an array parameter that specifies the length
var c=new array (1,2,3, 4, "a");//An array of five elements
/* The addition of array elements * *
var a=[];

Assign a value to the new index
a[0]= "zero";
A[1]= "one";

Add one or more element A.push ("two") to the end of the array by using the push () method;//
Adding an element
A.push ("Three", "four") to the end of the array;//Add two elements to the end of the array

// Add one or more element
a.unshift ("Yang") to the beginning of the array using the Unshift () method;
A.unshift ("Li", "Jia");
/* The deletion of array elements *
 /var b=[1,2,3];

Deletes an element with delete, but does not change the array length,
 delete b[0];//b no longer has element B.length at index 0
 ;//=>3;delete operation does not affect array length

//Use pop () method to delete the element, using the push () pairing, deleting an element from the end of the array, the length of the array minus one, and returning the deleted element
B.pop ();/delete and return b[2];

Use Shift (), which is paired with Unshift (), deletes from the head of the array, and returns the deleted elements, followed by the elements moving forward
b.shift ();

Finally, Splie () is a common method for inserting, deleting, and replacing elements of an array;
/* Create multidimensional arrays, the middle of JavaScript supports true multidimensional arrays, but can be approximated by arrays of arrays */
    /Create a multidimensional array
    var table=new array;//table has 10 lines
    for (Var i=0;i<table.length;i++) {
        table[i]=new array;//table has 10 columns; Here's a two-dimensional array of table[10][10]
    For
    (Var row=0;row<table.length;row++) {for
        (var col=0;col<table[row].length;col++) {
            table[ Row][col]=row*col
        }
    }
    Using multidimensional array query results
    var product=table[5][7];//35
/* Traversal array *
/var arr=[1,2,3,3,4];
1. Native for loop
for (Var i=0;i<arr.length;i++) {
    //log group Operation
}
//2.for in loop for
    (var i in arr) {
        Alert (Arr[i]);
        operate on an array of pairs
    }
//3.foreach
  var sum=0;
  Arr.foreach (function (x) {//pass each element of the array to this function
      //sum+=x;
      Here the elements in the array are operated
});
Finally, if you consider the performance, it is best to use the native for loop.

Array Method

-Join ();

The/*array.join () method converts all elements in an array to strings and joins together, finally returning the generated string, optionally specifying a string to separate the elements of the array, if no default is comma
/var arr=[1,2,3];
A.join ();//"1,2,3"
a.join ("");//"123"
//array.join () The reverse operation is the Array.split () method, the latter is to split the string into several blocks to create an array

-Reverse ();

The/*array.reverse () method is to reverse the order of the elements in the array and return an array of reverse orders */
var arr=[1,2,3];
Arr.reverse ();//=> "3,2,1"

-Sort ();

The/*array.sort () method sorts the elements in the array and returns the sorted array, where the array elements are arranged in alphabetical order when the call sort () without arguments, and if the array contains undefined elements, they are arranged at the end of the array/
var a=[. Banana "," cherry "," Apple "];
A.sort ();//=> "[Apple", "banana", "cherry"] ";

/* If you want to arrange in the order you want, you can pass a comparison function to sort (); If the first argument is to be in front, you should return a value less than 0 or else return a value greater than 0
/var a=[33,4,1111,22];
A.sort ();//=>1111,222,33,4;
A.sort (function (a,b) {return
    a-b;
}); /4,33,222,1111

-Concat ();

The/*array.concat () method creates and returns a new array whose elements include elements from the original array that called CONCAT () and concat () Each of these arguments. If any of these parameters are arrays, then the elements of the array are concatenated, not the array itself, but note that concat () does not recursively flatten the array of arrays, concat () does not modify the array of calls/
var a=[1,2,3];
A.concat ()//return [1,2,3];
A.concat (4,5);/return [1,2,3,4,5];
A.concat ([4,5]);/return [1,2,3,4,5];
A.concat ([4,5],[6,7]);/return [1,2,3,4,5,6,7];
A.concat (4,[5,[6,7]]);//return [1,2,3,4,5,[6,7]];

-Slice ();

The/*array.slice () method returns a fragment of the specified array or a sub array
/var arr=[1,2,3,4,5]
//If two arguments are passed in, array. Slice (startindex,endindex); Returns the elements of the index from StartIndex to endIndex-1;
Arr.slice (0,3);//return [1,2,3];
If only one argument is passed, then all elements Arr.slice (3) of the index to the end of the array are returned
;/return [4,5];
If there is a negative number in the argument, it represents the position relative to the last element of the array, for example: parameter-1 Specifies the last element,
Arr.slice (1,-1), or return [2,3,4];
Arr.slice ( -3,-2);/return [3];

-Splice ();

The/*array.aplice () method is a common method for inserting or deleting elements in an array, unlike slice (), concat (). Splice () modifies the array of calls *////
*
    Splice () The first parameter specifies the starting position of the insertion or deletion, the second parameter specifies the number of elements to delete, and if the second argument is omitted, all elements from the starting point to the end of the array are deleted/            
*
var arr=[1,2,3,4,5,6,7,8];
A.splice (4);/return [5,6,7,8];arr is [1,2,3,4];
A.splice (1,2)/return [2,3];arr is [1,4];

The third or any number of parameters of the splice (), specifying the element var a=[1,2,3,4,5] that needs to be inserted into the array
;
A.splice (2,0, ' A ', ' B ');/return [];a is [1,2, ' A ', ' B ', 3,4,5];
A.splice (2,2, ' [1,2],3);/return [' A ', ' B '];a is [1,2,[1,2],3,3,4,5];

-Push () &&pop ();

The/*push () and Pop () methods allow you to add one or more elements to the end of the array using the */
//push () method, and return the new length//pop () of the array, by
Removing an element from the end of the array and returning the deleted element

-Unshift () &&shift ();

/*unshift () &&shift () uses the array as a queue to use/
//unshift (), adds one or more elements to the header of the array, moves the existing element back, and finally returns the child's new array length
//shift () To delete and return the first element of the array, and then move the following elements forward

-tostring&&tolocalestring ();

/* The array has the ToString () method as well as other JavaScript objects. For an array, the method converts its element not to a string/
[1,2,3].tostring ();//Output 1,2,3

/*tolocalestring () is a localized version of the ToString () method. It invokes the toLocaleString () method of the element to convert each numeric element to a string and the generated string using a localized separator connection.

array Methods in ECMAScript 5

ForEach ();

The/*foreach () method traverses the array from beginning to end, calling the specified function for each element. As described above, the function passed as the first parameter of foreach (), then foreach () calls the function with three arguments: array elements, element indices, and arrays themselves/
var data=[1,2,3,4,5];
Computes the value of an array element
var sum=0;
Data.foreach (function (x) {
    sum+=x;
});
The value of each element is added to 1
data.foreach (function (Value,i,arr) {
    arr[i]=value+1;
})
dara;//[2,3,4,5,6];
Note: ForEach () cannot terminate the traversal before all elements are passed to the calling function.

map ();

The/*map () method passes each element of the called array to the specified function and returns an array that contains the return value of the function * *
var a=[1,2,3];
var b=a.map (function (x) {return
    x*x;
}); /B[1,4,9];
Note: Map () returns a new array, and a function passed to the map should have a return value

filter ();

The/*filter () method filters the array, and filter () accepts a function to logically determine whether the function returns TRUE or FALSE, and if the return value is true, the element is a member of the new array */
var a=[1,2,3,4,5];
var b=a.filter (function (x) {
    return  x>3;
}) b[4,5];
Note: filter () skips missing elements in a sparse array, and it returns always dense.

every () &&some ();

The/*every () and some () methods are logical judgments of arrays; they are judged by applying the specified function to the array element; The return value is True or false*/
//every () method; for all; if and only if all array elements return true ; return true;
a=[1,2,3];
A.every (function (x) {return
    x>0;
}) Returns true;
the//some () method; is a quantifier; Returns True when a qualifying condition exists in the array;
a.some (function (x) {return
    x<0;
}); /return false;

reduce () &&reduceright ()

The/*reduce () &&reduceright () method uses the specified function to combine the elements of an array, generating a single value
//*reduce () requires two parameters, the first is the function that performs the simplification operation. The task of simplifying a function is to use some method to combine or simplify two values into one value and return the value after simplification. The second (optional) parameter is an initial value passed to the function/
var a=[1,2,3,4,5];
var sum=a.reduce (Functon (x,y) {return
    x+y;
},0);//sum=15
; The Reduceright () method merges an array by index from high to low, with the same purpose as reduce ().

indexOf () &&lastindexof ();

/*indexof () and LastIndexOf () searches the entire array for elements with a given value, returns the index of the first element being searched, or if no return -1;indexof () is found While LastIndexOf () is reversed.
They accept two parameters: the first parameter represents the element to look for, the second parameter represents an index, the search starts at the index, and the second parameter can be omitted; */var a=[0,1,2,1,0]; A.indexof (1);//The return value is 1 a.lastindexof (1);//The return value is 3; a. IndexOf (3);//return value is-1; 
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.