Primary operation of the array JS

Today, because of a troublesome demand needed to get an array of operations, and simply looked on operating js array of articles and a number of related use methods, we want to help, of course, because of the time of writing are some of the basic method, the latter have something to write about the time of the application of it.

First, define an array: var arr = [1,2,3,4];

One, arr.push (1);

Was added, and the result [4, 1]

二、arr.unshift(1);

Added earlier, the result [1,1,2,3,4]

Three, arr.pop ();

To delete a post from the results [1,2,3]

Four, arr.shift ();

To delete a past results [2,3,4]

Five, splice method

5.1, delete operations: arr.splice (0,2); Results [3,4]

() The number in the range to delete, delete some meaning from what position

5.2, replace operation: arr.splice (0,1, x); results [x, 2,3,4]

5.3, add operation: arr.splice (1,0, x); results [1, x, 2,3,4]

x may be a number, arr.splice (1,0, x, y, z); results [1, x, y, z, 2,3,4]

The first number is the position, if it is 0, then the newly added on top

5.4, ​​split operation

was arr = 'abcghyuj'

arr.splice(”);

Results [a, b, c, g, h, y, u, j]

Six, sort sorting method

6.1、var arr = [c,a,b,d];

arr.sort (); result: [a, b, c, d] in accordance with the character code numbers to sort.

6.2, was arr = [3,23,1,4,];

arr.sort (); Results: [1,23,3,4] in descending order according to a first.

6.3, the digital size of the sort

arr.sort(function(a,b){

// output is the positive sequence

return a-b;(www.gendan5.com)

});

arr.sort(function(a,b){

// output in reverse order

return b-a;

});

arr.sort(function(a,b){

// random order

return Math.random() – 0.5;

});

If it is with the unit (the same) number can use parseInt () to convert to compare.

Seven of the array merge concat

var out = [1,2,3];

was arrb = [4,5,6];

was ARRC = [7,8,9]

arra.concat(arrb,arrc)

The results are: [1,2,3,4,5,6,7,8,9]

Eight, the array is reversed

was arr = [1,2,3];

arr.reverse();

Results: [3,2,1]

The contents of the array in turn order.

Guess you like

Origin blog.51cto.com/14513127/2432660