A method that changes the original array

1.pushAdd new elements to the end of the array (you can add more than one at a time)

Return value: length of the new array

var arr = [ ]; arr[0] = 1; arr[1] = 2; arr.push(3); / / [1, 2, 3]; Arr. Push (5, 6, '7') / / / 1,2,3,5,6, '7'Copy the code

2.unshiftAdd new elements to the front of the array (you can add more than one at a time)

Return value: length of the new array

**

var arr = [ ]; arr.unshift(4); // result is [4]; Arr. Unshift (1, 2, 3) / / [1, 2, 3, 4]Copy the code

3.popDeletes an element at the end of the array

Return value: deleted element

**

var arr = [ ]; arr[0] = 1; arr[1] = 2; arr[2] = 3; arr.pop(); / / result is [1, 2];Copy the code

4.shiftRemoves the first element of the array

Return value: deleted element

var arr = [ ]; arr[0] = 1; arr[1] = 2; arr[2] = 3; arr.shift(); / / result is [2, 3];Copy the code

5.spliceDelete, add, replace elements in an array (powerful ~~~)

Return value: Returns a new array containing the deleted element, if any.

Syntax: array.splice(index, howmany, item1,..... ,itemX) parameter :\ index: required. Integer to specify where items are added/removed, and negative numbers to specify positions from the end of the array. Howmany: Required. Number of items to delete. If set to 0, the project will not be deleted. Item1,... , itemX: Optional. The new item added to the array.Copy the code

Usage:

5.1 Deleting Elements

**

let a = [1, 2, 3, 4, 5, 6, 7]; Let item = a.splice(0, 3); / / [1, 2, 3]. The console log (a); Let item = a.ice (-1, 3); let item = a.ice (-1, 3); / / [7]Copy the code

5.2 Delete and Add

**

let a = [1, 2, 3, 4, 5, 6, 7]; // Start from array subscript 0, delete 3 elements, add element 'add' let item = a.splice(0,3,' add '); / / [1, 2, 3]. The console log (a); // [' add ',4,5,6,7] // add two elements' add 1',' add 2' let item = a.splice(-2,3,' add 1',' add 2'); / / [6, 7]. The console log (a); // [1,2,3,4,5,' add 1',' add 2']Copy the code

5.3 Do not Delete only Add

**

let a = [1, 2, 3, 4, 5, 6, 7]; Let item = a.splice(0,0,' add 1',' add 2'); // [] Returns empty array console.log(a) without deleting elements; / / / 'add 1', 'added 2', 1,2,3,4,5,6,7] let the item = a.s plice (1, 0, 'added 1', '2'); // [] Returns empty array console.log(a) without deleting elements; // [1,2,3,4,5,6,' Add 1',' Add 2',7] Adds two elements before the last elementCopy the code

6. reverseFlip the array

**

Let a = [1, 2, 3]; a.reverse(); console.log(a); / / [3, 2, 1]Copy the code

7. sortSort an array

Parameter Optional: Comparison function that specifies the sort order. By default, if the sort() method does not pass a comparison function, it defaults to an alphabetical ascending order. If the element is not a string, the toString() method is called to convert the element to the Unicode point of the string, and then the characters are compared.

**

Var a = ["Banana", "Orange", "Apple", "Mango"]; a.sort(); Var a = [10, 1, 3, 20,25,8]; // ["Apple","Banana","Mango","Orange"] The console. The log (a.s ort ()) / /,10,20,25,3,8 [1];Copy the code

The comparison function of sort takes two default arguments, which are the two elements in the array to be compared. Normally we use a and b to receive two elements to be compared:

  • If the comparison function returns a value <0, then A comes before B;
  • If the comparison function returns 0, the relative positions of a and B remain the same;
  • If the comparison function returns a value greater than 0, then b comes before A;

The elements of an array are in ascending or descending order:

**

Var array = [10, 1, 3, 4,20,4,25,8]; Array. sort(function(a,b){return (a,b){return a,b; }); console.log(array); / /,3,4,4,8,10,20,25 [1]; Array. sort(function(a,b){return b-a; }); console.log(array); / /,20,10,8,4,4,3,1 [25];Copy the code

8.copyWithinMembers at the specified location are copied to other locations (ES6)

Definition: Copies a member of the specified location to another location inside the current array and returns the array. Syntax: array.copywithin (target, start = 0, end = this.length) parameters: All three parameters are numeric, and if they are not, they are automatically converted to numeric. Target (required) : Replaces data from this position. If it is negative, it is the reciprocal. Start (Optional) : reads data from this position. The default value is 0. If it is negative, it is the reciprocal. End (Optional) : Stops reading data until this position, which is equal to the array length by default. Use negative numbers to specify positions from the end of the array. Browser compatibility (MDN): chrome 45,Edge 12,Firefox32,Opera 32,Safari 9, IE not supported

**

// Select * from *; 1 of 4 [1, 2, 3, 4, 5]. CopyWithin (0, 2, 1) / / [4, 2, 3, 4, 5] var a = [' OB1 ', 'Koro1', 'OB2', 'Koro2', 'OB3', 'Koro3', 'OB4', 'Koro4', 'OB5', 'Koro5'] / / 2 position began to be replaced, 3 start reading to replace 5 location stop in front of the replacement A.c opyWithin,3,5 (2) / / [" OB1, "" Koro1", "Koro2", "OB3," "OB3," "Koro3", "OB4", "Koro4", "OB5", "Koro5"]Copy the code

From the above example: the first argument is the position of the element to be replaced. The range of data positions to be replaced: from the second argument is the element to be read, before the third argument an element stops reading the length of the array does not change

9.fillFill an array with the given value (ES6)

Parameters: first element (required): the value of the array to fill second element (optional): the start of the fill, default is 0 third element (optional): the end of the fill, default is arr.length

**

['a', 'b', 'c'].fill(7)
// [7, 7, 7]
['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']
Copy the code

Methods that do not change the original array

1.joinThe join() method separates all the elements of an array into a string using the specified delimiter and returns the resulting string

**

let a= ['hello','world']; let str=a.join(); // 'hello,world' // specifies the delimiter to be used. The default delimiter is comma. // 'hello+world'Copy the code

When using the Join method or the toString method described below, what happens when the elements of an array are also arrays or objects?

**

let a= [['OBKoro1','23'],'test']; let str1=a.join(); / / OBKoro1, 23, test the let b = ({name: 'OBKoro1, age:' 23 '}, 'test']. let str2 = b.join(); // [object object],test // Object to string recommended json.stringify (obj);Copy the code

The join()/toString() method calls join()/toString() when the elements of an array are arrays. If the elements are objects, the objects are converted to object object strings.

2. ToLocaleString Array conversion string, which returns a string representing an array element. The string consists of the toLocaleString() return values for each element in the array joined (separated by commas) by calling the join() method.

**

let a=[{name:'OBKoro1'},23,'abcd',new Date()]; let str=a.toLocaleString(); // [object Object],23, abCD,2018/5/28 PM 1:52:20Copy the code

Each element in the array calls its own toLocaleString method. An object calls the object’s toLocaleString. A Date calls Date’s toLocaleString.

The toString() method converts an array to a comma-linked string (not recommended).

The effect of this method is the same as that of the JOIN method, which is used to convert arrays to strings. However, compared with the Join method, this method has no advantages and cannot customize string delimiters. Therefore, it is not recommended to use this method. Ps: Js calls this method to convert an array to a string automatically when operating on an array or string

**

Let b= ['toString',' demo '].toString(); // toString, demo let a= [' call toString',' connect after me ']+' la la la la '; // Call toString, link after me la la laCopy the code

This method returns a shallow copy of a portion of the selected array from the beginning to the end (not including the end) into a new array object without modifying the original array.

Ps: Strings also have a slice() method that extracts strings, not to be confused. Parameter: BEGIN (Optional): The value of the index, which accepts negative values, from which elements in the original array are extracted. The default value is 0. End (Optional): index value (excluding), accepts a negative value, and ends at the end of the index. The default value is the end of the array (including the last element).

**

let a= ['hello','world']; Let b = a.s lice (0, 1); // ['hello'] a[0]=' change array '; console.log(a,b); // [' change array ','world'] ['hello'] b[0]=' change array '; console.log(a,b); // [' change array ','world'] [' change array copied ']Copy the code

As above, the new array is shallow-copied, the elements are simple data types, and changes do not interfere with each other.

If it’s a complex data type (object, array), changing one of them will change the other

**

let a= [{name:'OBKoro1'}]; let b=a.slice(); console.log(b,a); / / / {" name ":" OBKoro1}] [{" name ":" OBKoro1} "] / / a [0]. Name = 'to change the original array; // console.log(b,a); / / / {" name ":" to change the original array "}] [{" name ":" to change the original array "}] [0]. / / b name = 'change copy an array, b [0]. Belonged to =' change copy array; / / / {" name ":" change copy an array ", "belonged to" : "change copy an array"}] [{" name ":" change copy an array ", "belonged to" : "change copy an array"}]Copy the code

The reason is explained above: slice() is a shallow copy. For complex data types, a shallow copy copies only Pointers to the original array, so changing either the original array or the shallow-copied array changes the original array’s data. .

**

let a = [2, 3, 4, 5] let b = [ 4,...a, 4, 4] console.log(a,b); // [2, 3,4,5] [4,2,3,4, 4]Copy the code

5. IndexOf checks whether an element exists in an array and returns the index. Returns the first index in the array where a given element can be found, or -1 if none exists.

Parameters: searchElement(required): the element to be searched fromIndex(optional): the location to start the search (cannot be greater than or equal to the length of the array, returns -1), accepts negative values, defaults to 0. Strict equality search: Unlike string indexOf, array indexOf searches for elements using strict equality ===, that is, array elements must match exactly to be searched. Note: indexOf() does not recognize NaN

**

Let a = [' la-la-la, 2,4,24, NaN]. The console log (Anderson ndexOf (', ')); // -1 console.log(a.indexOf('NaN')); // -1 console.log(a.indexof (' la la ')); / / 0Copy the code

6.concatMerge array

**

Var arr = [1, 2, 3]; Var arr1 = (4 and 6); var arr2 = arr.concat(arr1); console.log(arr2); / / [6].Copy the code

Merge array method 2: (ES6 expansion operator)[…arr,…arr2]

7.lastIndexOfFinds the last position of the specified element in the array. The array_index () method returns the index of the last element in the array, or -1 if none exists. (Look up from the back of the array)

Parameters: searchElement(required): the element to be searched fromIndex(Optional): Reverse lookup starting position, default array length -1, that is, find the entire array. There are three rules about fromIndex: positive values. If the value is greater than or equal to the length of the array, the entire array is searched. A negative value. Think of it as an offset forward from the end of the array. (e.g. -2, starting from the last second element of the array) negative. If the absolute value is greater than the array length, the method returns -1, that is, the array will not be looked up.

**

Let a = [' OB ', 4, 'Koro1', 1, 2, 'Koro1, three, four, five,' Koro1]; // let b= a.listIndexof ('Koro1',4); // let b= a.listIndexof ('Koro1',4); // let b= a.listIndexof ('Koro1',100); // let b= a.listIndexof ('Koro1',100); // let b= a.lastIndexof ('Koro1',-11); Let b= a.listIndexof ('Koro1',-9); let b= a.listIndexof ('Koro1',-9); // Look forward to the second element, 4. If no element is found, return -1Copy the code

8.includesFind if an array contains an element and return a Boolean (ES7)

Parameters: searchElement(required): the element being searched fromIndex(optional): The default value is 0. The parameter indicates the start of the search and accepts negative values. If the value exceeds the array length, the array will not be searched, return false. Negative absolute value exceeds long array degree, reset to search from 0. \

The includes method is designed to make up for the shortcomings of the indexOf method: The indexOf method does not recognize NaN. The indexOf method is not semantic enough to check whether a value is not equal to -1

**

let a=['OB'.'Koro1'.1.NaN];
// let b=a.includes(NaN); // true identifies NaN
// let b=a.includes('Koro1',100); // false Does not search beyond the array length
// let b=a.includes('Koro1',-3); // true searches from the third to last element
// let b=a.includes('Koro1',-100); // true Searches the entire array if the absolute value exceeds the length of the array
Copy the code

9.Array.fromConverting pseudo-arrays to real arrays (ES6)

Pseudoarray objects: (Function arguments object,set data structure, etc…) Has the length attribute, but cannot use the push,unshift, and other methods in the real array

/ / 1. The pseudo array object let obj = {0: 'a', 1: 'b', 2: 'c', length: 3}; let arr = Array.from(obj); // ['a','b','c']; // 2. Data structures with Iterator interfaces such as strings, sets, NodeList objects let arr = array. from('hello'); // ['h','e','l','l'] let arr = Array.from(new Set(['a','b'])); // ['a','b']Copy the code