JS array commonly used method of operation

in #life7 years ago

1, push to add the last item
Add an item at the end of the array, and return the length of the array, you can add any type of value as an array.
var arr = [1,2]; arr.push (6) // arr: [1,2,6] arr.push ('aa') // arr: [1,2,6, "aa"] arr .push (undefined) // arr: [1,2,6, "aa", undefined] arr.push ({a: "A", b: "B"}) // [1,2,6, " aa ", undefined, {a:" A ", b:" B "}]

2, unshift add the first one
var arr = [1,2]; arr.unshift (9) // [9,1,2] arr.unshift ('aa') // ['aa', 9,1,2]

3, pop delete the last one
Delete the last item, and return the value of the delete element; undefine if the array is empty. The array itself operation
arr.pop () // arr: [1, 2, 3, 4] arr.pop () // arr: [1, 2, 3] var arr = [1,2,3,4,5]

4, shift delete the first one
var arr = [1,2,3,4,5]; arr.shift () // [2, 3, 4, 5] arr.shift () // [3, 4, 5]

5, slice Intercept (slice) array Intercepted array
Do not change the original array, get a new array
var a = arr.slice (1) // a: [2,3,4,5] var a = arr.slice (1, 2, 3, 4, 5) 1,3) // a: [2,3] var a = arr.slice (3,4) // a: [5]

6, splice splicing array
Change the original array can be deleted before the shift, pop delete, increase before unshift, after adding the same effect with the push. The index starts from 0
splice (index, howmany, item1, ....., itemX) var arr = [1,2,3,4,5]; push: arr.splice (arr.length, 0, 6) // [1, 2, 3, 4, 5, 6] unshift: arr.splice (0, 0, 6) // [6, 1, 2, 3, 4, 5] pop: arr.splice (arr.length-1, 1 ) // [1, 2, 3, 4] shift: arr.splice (0, 1) // [2, 3, 4, 5] arr.splice (1) // [1] arr.splice (1, 2) // [1, 4, 5] arr.splice (1, 0, 'A') // [1, "A", 2,3,4, 5] arr.splice ',' B ') // [1, "A", "B", 4, 5]

7, concat array merged
to get a new array, the array does not change the element var arr1 = [1,2]; var arr2 = [3,4,5]; var arr = arr1.concat (arr2) // [1,2 , 3,4,5]

8, indexOf array element index
And return the element index, does not exist Returns -1, the index starts from 0
var arr = ['a', 'b', 'c', 'd', 'e']; arr.indexOf ('a'); //0arr.indexOf(a); // - 1arr.indexOf 'f'); //-1arr.indexOf ('e'); // 4

9, join the array to the string
var a, b; a = [0, 1, 2, 3, 4]; b = a.join ("-"); // 0-1-2-3-4

10, reverse array flip
And return to the original array flip, the original array flip
var a = [1,2,3,4,5]; a.reverse () // a: [5, 4, 3, 2, 1] returns [5, 4, 3, 2, 1]

Coin Marketplace

STEEM 0.17
TRX 0.13
JST 0.027
BTC 61098.19
ETH 2625.94
USDT 1.00
SBD 2.63