Summary of common methods of array

1, Will change the method of the original array

1.push   Add a new element to the end of the array (multiple elements can be added at one time)

Return value: the 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 code

2.unshift   Add a new element to the front of the array (multiple elements can be added at one time)

Return value: the length of the new array

**

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

3.pop   Deletes 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 code

4.shift   Deletes 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 code

5.splice   Delete, add and replace elements in the array (extremely powerful ~ ~ ~)

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

Syntax: array.splice(index, howmany, item1,.....,itemX)
parameter:\
index: Required. Integer, specifying addition/Delete the position of the item. Use a negative number to specify the position from the end of the array.

howmany: Required. Number of items to delete. If set to 0, the item is not deleted.

item1, ..., itemX:  Optional. Adds a new item to the array.
Copy code

Usage:

5.1 deleting elements

**

let a = [1, 2, 3, 4, 5, 6, 7];
// Delete 3 elements starting with array subscript 0
let item = a.splice(0, 3); // [1,2,3]
console.log(a); // [4,5,6,7]
// Three elements are deleted from the last element, and only 7 are deleted because of the last element
let item = a.splice(-1, 3); // [7]
Copy code

5.2 delete and add

**

let a = [1, 2, 3, 4, 5, 6, 7];
// Starting from the array subscript 0, delete 3 elements and add the element 'Add'
let item = a.splice(0,3,'add to'); // [1,2,3]
console.log(a); // ['Add', 4,5,6,7]
// Starting from the last and second element of the array, delete three elements and add two elements' add 1 'and' add 2 '
let item = a.splice(-2,3,'Add 1','Add 2'); // [6,7]
console.log(a); // [1,2,3,4,5, 'add 1', 'add 2']
Copy code

5.3 add without deleting

**

let a = [1, 2, 3, 4, 5, 6, 7];
let item = a.splice(0,0,'Add 1','Add 2'); // [] no element deleted, return empty array
console.log(a); // ['add 1', 'add 2', 1,2,3,4,5,6,7]
let item = a.splice(-1,0,'Add 1','Add 2'); // [] no element deleted, return empty array
console.log(a); // [1,2,3,4,5,6, 'add 1', 'add 2', 7] add two elements before the last element
 Copy code

six   reverse   Flip array

**

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

seven   sort   Array sorting

Optional parameter: a comparison function that specifies the sort order.
By default, if the sort() method does not pass the comparison function, it is in alphabetical ascending order by default. If the elements are not strings, the toString() method will be called to convert the elements into Unicode (universal code) sites of strings, and then compare the characters.

**

// String arrangement
var a = ["Banana", "Orange", "Apple", "Mango"];
a.sort(); // ["Apple","Banana","Mango","Orange"]
// When sorting numbers, some numbers will be ranked later after being converted to Unicode strings
var a = [10, 1, 3, 20,25,8];
console.log(a.sort()) // [1,10,20,25,3,8];
Copy code

Compare the two parameters of the function
The comparison function of sort has two default parameters. To receive these two parameters in the function, these two parameters are the two elements to be compared in the array. Usually, we use a and b to receive the two elements to be compared:

  • If the return value of the comparison function is < 0, then a will be in front of b;
  • If the return value of the comparison function = 0, the relative positions of a and b remain unchanged;
  • If the return value of the comparison function is > 0, then b will be in front of a;

Common usage of sort sort
The array elements are in ascending and descending order of numbers:

**

var array = [10, 1, 3, 4,20,4,25,8];
// Ascending order A-b < 0 a will be placed in front of b and sorted according to the size of A 
// For example, the subtracted a is 10, the subtracted is 20, 10-20 < 0, and the subtracted a(10) precedes the subtracted b(20) 
array.sort(function(a,b){
 return a-b;
});
console.log(array); // [1,3,4,4,8,10,20,25];
// The descending minuend and the subtraction are exchanged for 20-10 > 0. The minuend b(20) is in front of the subtraction a(10)
array.sort(function(a,b){
 return b-a;
});
console.log(array); // [25,20,10,8,4,4,3,1];
Copy code

Array multi conditional sorting

**

var array = [{name:'Koro1'},{name:'Koro1'},{name:'OB'},{name:'Koro1'},{name:'OB'},{name:'OB'}];
array.sort(function(a,b){
 if(a.name === 'Koro1'){// If name is' Koro1 ', return - 1, - 1 < 0, and a is in front of b
  return -1
 }else{ // If not, a comes after b
  return 1
 }
})
// [{"name":"Koro1"},{"name":"Koro1"},{"name":"Koro1"},{"name":"OB"},{"name":"OB"},{"name":"OB"}] 
Copy code

Custom comparison function

**

var array = [{name:'Koro1'},{name:'Koro1'},{name:'OB'},{name:'Koro1'},{name:'OB'},{name:'OB'}];
array.sort(function(a,b){
 if(a.name === 'Koro1'){// If name is' Koro1 ', return - 1, - 1 < 0, and a is in front of b
  return -1
 }else{ // If not, a comes after b
  return 1
 }
})
// [{"name":"Koro1"},{"name":"Koro1"},{"name":"Koro1"},{"name":"OB"},{"name":"OB"},{"name":"OB"}] 
Copy code

8.copyWithin   Copy members from the specified location to another location (es6)

Definition: within the current array, copy the members of the specified location to other locations, and return the array.
Syntax: array.copyWithin(target, start = 0, end = this.length)
Parameters:
All three parameters are numerical values. If not, they will be automatically converted to numerical values
target (required): replace data from this location. If it is negative, it indicates the reciprocal.
Start (optional): start reading data from this location. The default value is 0. If it is negative, it indicates the reciprocal.
End (optional): stop reading data before reaching this position. By default, it is equal to the length of the array. Use a negative number to specify a position from the end of the array.
Browser compatibility (MDN): Chrome 45, edge 12, Firefox 32, opera 32, Safari 9, ie does not support it

**

// -2 is equivalent to position 3 and - 1 is equivalent to position 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']
// Position 2 starts to be replaced, position 3 starts to read the position to be replaced, and the replacement stops before position 5
a.copyWithin(2,3,5)
// ["OB1","Koro1","Koro2","OB3","OB3","Koro3","OB4","Koro4","OB5","Koro5"] 
Copy code

From the above example:
The first parameter is the position of the element to be replaced
The location range of the data to be replaced: the second parameter is the element that starts reading, and the element before the third parameter stops reading
The length of the array does not change
After reading several elements, replace several elements from the place where they were replaced

9.fill   Fills an array with the given value (es6)

Parameters:
First element (required): the value to populate the array
Second element (optional): the starting position of the fill. The default value is 0
The third element (optional): the end position of the filling. The default is arr.length

**

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

2, The method of the original array will not be changed

1.join   Array to string. The join() method is used to separate all elements in the array by the specified separator, put them into a string, and return the generated string

**

let a= ['hello','world'];
let str=a.join(); // 'hello,world'
//Specifies the delimiter to use, which is comma by default
let str2=a.join('+'); // 'hello+world'
Copy code

When using the join method or the toString method mentioned below, what happens when the elements in the array are also arrays or objects?

**

let a= [['OBKoro1','23'],'test'];
let str1=a.join(); // OBKoro1,23,test
let b= [{name:'OBKoro1',age:'23'},'test'];
let str2 = b.join(); // [object Object],test
// JSON.stringify(obj) is recommended for converting objects to strings;
Copy code

When the array element is an array, the join()/toString() method will also call join()/toString() for the array. If it is an object, the object will be converted to [object Object] string.

2.toLocaleString array to string and returns a string representing array elements. The string consists of the return value of toLocaleString() of each element in the array connected (separated by commas) by calling the join() method.

**

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

As mentioned above, chestnut: call the toLocaleString method of the array, and each element in the array will call its own toLocaleString method. The object calls the toLocaleString of the object, and the Date calls the toLocaleString of the Date.

3. toString array to string. toString() method can convert the array to a comma linked string (not recommended)

The effect of this method is the same as that of the join method. It is used to convert an array to a string. However, compared with the join method, this method has no advantages and cannot customize the delimiter of the string, so it is not recommended.
ps: when array and string operations are performed, js will call this method to automatically convert the array into a string

**

let b= [ 'toString','demonstration'].toString(); // toString, demo
let a= ['call toString','Connect behind me']+'La La La'; // Call toString and connect it behind me 
Copy code

4.slice intercepts the array and shallow copies the elements of the array. The method returns a part of the array selected from start to end (excluding end) and shallow copies it to a new array object, and the original array will not be modified.

ps: the string also has a slice() method to extract the string. Don't confuse it.
Parameters:
Begin (optional): index value. Negative values are accepted. Elements in the original array are extracted from the index. The default value is 0.
End (optional): index value (excluding), accept negative value, end extracting the original array element before the index, and the default value is the end of the array (including the last element).

**

let a= ['hello','world'];
let b=a.slice(0,1); // ['hello']
a[0]='Change original array';
console.log(a,b); // ['change original array', 'world'] ['hello']
b[0]='Change the array of copies';
 console.log(a,b); // ['change original array', 'world'] ['change copied array']
Copy code

As above: the new array is a shallow copy, and the elements are simple data types. After changing, they will not interfere with each other.

If it is 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 = 'change original array';
// console.log(b,a); // [{"name": "change original array"}] [{"name": "change original array"}]
// b[0].name = 'change copy array', b[0].koro = 'change copy array';
// [{"name": "change copy array", "koro": "change copy array"}] [{"name": "change copy array", "koro": "change copy array"}]
Copy code

The reason is mentioned above in the definition: slice() is a shallow copy. For a shallow copy of complex data types, only a pointer to the original array is copied. Therefore, whether the original array or the shallow copy array is changed, the data of the original array is changed.

**

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

5.indexOf finds whether an element exists in the array and returns the subscript. Returns the first index of a given element that can be found in the array. If it does not exist, it returns - 1.

Parameters:
Searchelement (required): the element to be found
Fromindex (optional): the position to start searching (cannot be greater than or equal to the length of the array, return - 1), accept negative values, and the default value is 0.
Strictly equal search:
The indexOf search of the array is different from that of the string. The indexOf the array uses strict equality = = = search elements, that is, the array elements must be completely matched to succeed in the search.
Note: indexOf() does not recognize NaN

**

let a=['gossip',2,4,24,NaN]
console.log(a.indexOf('la')); // -1 
console.log(a.indexOf('NaN')); // -1 
console.log(a.indexOf('gossip')); // 0
 Copy code

6.concat   Merge array

**

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

Merge array method 2: (es6 expand operator) [... Arr,... Arr2]

7.lastIndexOf   Finds the last position of the specified element in the array. Method returns the index of the last element in the array. If it does not exist, it returns - 1. (look up from the back of the array)

Parameters:
Searchelement (required): the element to be found
Fromindex (optional): the start position of reverse search. The default value is the length of the array - 1, that is, the whole array is searched.
There are three rules about fromIndex:
positive. If the value is greater than or equal to the length of the array, the entire array is searched.
Negative value. Treat it as an offset forward from the end of the array. (for example, - 2, search from the last and second element of the array)
Negative value. If its absolute value is greater than the length of the array, the method returns - 1, that is, the array will not be searched.

**

let a=['OB',4,'Koro1',1,2,'Koro1',3,4,5,'Koro1']; // The array length is 10
// let b=a.lastIndexOf('Koro1',4); //  Look forward from subscript 4 and return to subscript 2
// let b=a.lastIndexOf('Koro1',100); //  Greater than or the length of the array. Finding the entire array returns 9
// let b=a.lastIndexOf('Koro1',-11); // -1 array will not be found
let b=a.lastIndexOf('Koro1',-9); // Looking forward from the second element 4, if it is not found, it returns - 1
 Copy code

8.includes   Find whether the array contains an element and return Boolean (es7)

Parameters:
Searchelement (required): the element to be found
Fromindex (optional): the default value is 0. The parameter indicates the starting position of the search. Negative values are accepted. If the positive value exceeds the length of the array, the array will not be searched and false will be returned. If the negative absolute value exceeds the length of the array, reset the search from 0\

The includes method is used to make up for the defects of the indexOf method:
The indexOf method does not recognize NaN
The indexOf method checks whether a value is included, which is not semantic enough. It needs to judge whether it is not equal to - 1 and the expression is not intuitive enough

**

let a=['OB','Koro1',1,NaN];
// let b=a.includes(NaN); // true identify Nan
// let b=a.includes('Koro1',100); // false do not search if the array length is exceeded
// let b=a.includes('Koro1',-3); // true starts the search from the penultimate element 
// let b=a.includes('Koro1',-100); // true negative absolute value exceeds the length of the array. Search the entire array
 Copy code

9.Array.from   Convert pseudo arrays to real arrays (es6)

Pseudo array object: (arguments object of function, set data structure, etc.)   Has the length attribute, but cannot use push,unshift and other methods in the true array

// 1. Pseudo array object
let obj = {0: 'a', 1: 'b', 2:'c', length: 3};
let arr = Array.from(obj); // ['a','b','c'];
// 2. Deploy the data structures of the Iterator interface, such as string, Set and NodeList objects
let arr = Array.from('hello'); // ['h','e','l','l']
let arr = Array.from(new Set(['a','b'])); // ['a','b']

Tags: Javascript Vue.js

Posted on Wed, 29 Sep 2021 13:22:41 -0400 by andremta