Array is the most commonly used data set in JS, its built-in method has a lot of, master these methods, can effectively improve our work efficiency, but also has a great impact on the quality of our code.

Create an array

1. Use array literals

var arr4 = [];   // Create an empty array
var arr5 = [20];   // Create an array containing 1 item of data 20
var arr6 = ["lily"."lucy"."Tom"];   // Create an array of three strings
Copy the code

2. Use the Array constructor

No arguments structure

var arr1 = new Array(a);// Create an empty array
Copy the code

Take ginseng structure

If only one numeric argument is passed, an empty array with the specified initial length is created

var arr2 = new Array(20);   // Create an array of 20 entries
Copy the code

If a non-numeric argument is passed or the number of arguments is greater than 1, an array containing the specified elements is created

var arr3 = new Array("lily"."lucy"."Tom");   // Create an array of three strings
var array4 = new Array('23'); / / / "23"
Copy the code

3.Array.of method to create arrays (new in ES6)

One of the goals of ES6’s new Array creation methods is to help developers avoid one of the quirks of the JS language when using Array constructors.

The array.of () method always creates an Array containing all the parameters passed in, regardless of their number or type.

let arr = Array.of(1.2);
console.log(arr.length);/ / 2

let arr1 = Array.of(3);
console.log(arr1.length);/ / 1
console.log(arr1[0]);/ / 3

let arr2 = Array.of('2');
console.log(arr2.length);/ / 1
console.log(arr2[0]);/ / '2'
Copy the code

4.Array.from method to create arrays (new in ES6)

Converting non-array objects into real arrays in JS is cumbersome. In ES6, array.from () returns an Array by passing an iterable or array-like object as the first argument.

function arga(. args) {  / /... Args Array of remaining arguments, supplied by the actual arguments passed to the function
    let arg = Array.from(args);
    console.log(arg);
}

arga('arr1'.26.'from'); // ['arr1',26,'from']
Copy the code

Mapping transformation

If you want to perform further Array conversions, you can pass a mapping function to the array.from () method as the second argument. This function converts each value of the array object into the target form and stores it at the corresponding location in the target array.

function arga(. args) {  
     return Array.from(args, value= > value + 1);
}

let arr = arga('arr'.26.'pop');
console.log(arr);//['arr1',27,'pop1']
Copy the code

If the mapping function needs to work on an object, you can manually pass a third argument to the array.from () method to specify this inside the mapping function

const helper = {
  diff: 1.add(value) {
    return value + this.diff; }}function translate() {
 // Arguments is an array-like object corresponding to the arguments passed to the function
  return Array.from(arguments, helper.add, helper); 
}

let arr = translate('liu'.26.'man');
console.log(arr); // ["liu1", 27, "man1"]
Copy the code

2. Array methods

The main array prototype methods are as follows

  • join(): concatenates each item of the array into a string using the specified delimiter
  • push(): adds a new element to the end of the array
  • pop(): Deletes the last item of the array
  • shift(): Deletes the first item of the array
  • unshift(): adds a new element to the top of the array
  • slice(): Finds some elements according to the conditions
  • splice(): Adds, deletes, and modifies arrays
  • fill()The: method can populate one or more elements of an array with specific values
  • filter(): Filter
  • concat(): Used to join two or more arrays
  • indexOf(): Checks the index of the first occurrence of the current value in the array
  • lastIndexOf(): Checks the index of the last occurrence of the current value in the array
  • every(): Determines whether each item in the array satisfies the condition
  • some(): Checks whether there are items in the array that satisfy the condition
  • includes(): Determines whether an array contains a specified value
  • sort(): Sorts the elements of an array
  • reverse(): Reverses the array order
  • forEach(): ES5 and below cycle through each item of the number group
  • map(): ES6 Loops through each item in the group
  • copyWithin(): copies elements from one specified location in the array to another specified location in the array
  • find(): Returns the matched value
  • findIndex(): Returns the index of the matching position
  • ToLocaleString (), toString (): Converts an array to a string
  • Flat (), flatMap (): Flattens arrays
  • Entries (), keys(), values(): Traverses the number group

The basic functions of each method are explained in detail

1.join()

The join() method converts all the elements in an array to a string.

Elements are separated by the specified delimiter. Use commas as separators by default

var arr = [1.2.3];
console.log(arr.join());   / / 1, 2, 3
console.log(arr.join("-"));   / / 1-2-3
console.log(arr);   // [1, 2, 3]
Copy the code

The join() method returns the repeated string by passing in the string and the number of repetitions as follows:

function repeatString(str, n) {
// An empty array of length n+1 is concatenated with strings to form a string
	return new Array(n + 1).join(str);
}
console.log(repeatString("abc".3));   // abcabcabc
console.log(repeatString("Hi".5));   // HiHiHiHiHi
Copy the code

2. Push () and pop ()

The push() method adds elements to the array from the end, and can add one or more elements.

The pop() method removes the last element of the array and returns the deleted element.

var arr = ["Lily"."lucy"."Tom"];
var count = arr.push("Jack"."Sean");
console.log(count);  / / 5
console.log(arr);   // ["Lily", "lucy", "Tom", "Jack", "Sean"]
var item = arr.pop();
console.log(item);   // Sean
console.log(arr);   // ["Lily", "lucy", "Tom", "Jack"]
Copy the code

3. The shift () and the unshift ()

The shift() method removes the first element from an array and returns the value of the first element.

The unshift() method adds one or more elements to the beginning of the array and returns the new length.

var arr = ["Lily"."lucy"."Tom"];
var count = arr.unshift("Jack"."Sean");
console.log(count);   / / 5
console.log(arr);   //["Jack", "Sean", "Lily", "lucy", "Tom"]
var item = arr.shift();
console.log(item);   // Jack
console.log(arr);   // ["Sean", "Lily", "lucy", "Tom"]
Copy the code

4.sort()

The sort() method is used to sort the elements of an array.

The sorting order can be alphabetic or numeric and in ascending or descending order.

The default sort order is alphabetical ascending.

var arr1 = ["a"."d"."c"."b"];
console.log(arr1.sort());   // ["a", "b", "c", "d"]
arr2 = [13.24.51.3];
console.log(arr2.sort());   // [13, 24, 3, 51]
console.log(arr2);   // [13, 24, 3, 51](tuple changed)
Copy the code

To solve the above problem, the sort() method can take a comparison function as an argument so that we can specify which value comes before which.

The comparison function takes two arguments and returns a negative number if the first argument should come before the second, 0 if the two arguments are equal, and a positive number if the first argument should come after the second. Here is a simple comparison function:

function compare(value1, value2) {
    if (value1 < value2) {
    	return -1;
    } else if (value1 > value2) {
   		return 1;
    } else {
    	return 0;
    }
}
arr2 = [13.24.51.3];
console.log(arr2.sort(compare));   // [3, 13, 24, 51]
Copy the code

If you want to use the comparison function to produce a descending sort, simply swap the values returned by the comparison function:

function compare(value1, value2) {
    if (value1 < value2) {
    	return 1;
    } else if (value1 > value2) {
    	return -1;
    } else {
    	return 0;
    }
}
arr2 = [13.24.51.3];
console.log(arr2.sort(compare));   // [51, 24, 13, 3]
Copy the code

5.reverse()

The reverse() method is used to reverse the order of elements in an array.

var arr = [13.24.51.3];
console.log(arr.reverse());   / / [13] 3, 51, 24,
console.log(arr);   //[3, 51, 24, 13]
Copy the code

6.concat()

The concat() method is used to join two or more arrays.

This method does not alter the existing array, but simply returns a copy of the concatenated array.

var arr = [1.3.5.7];
var arrCopy = arr.concat(9[11.13]);
console.log(arrCopy);   //[1, 3, 5, 7, 9, 11, 13]
console.log(arr);   // [1, 3, 5, 7]
Copy the code

As you can see from the above test results, if you pass in an array instead of an array, you add the parameters directly to the array. If you pass in an array, you add the items from the array to the array. But what if you pass in a two-dimensional array?

var arrCopy2 = arr.concat([9[11.13]]);
console.log(arrCopy2);   //[1, 3, 5, 7, 9, Array[2]]
console.log(arrCopy2[5]);   / / [11, 13]
Copy the code

7.slice()

Slice () : Returns a new array of items from the original array specified between the start and end subscripts.

The slice() method can take one or two arguments to return the start and end positions of the item.

In the case of a single argument, the slice() method returns all items from the position specified by that argument to the end of the current array.

If there are two arguments, the method returns the items between the start and end positions, but not the items at the end position.

When a negative number occurs, the negative number is replaced by the value of the array length (6)

var arr = [1.3.5.7.9.11];
var arrCopy = arr.slice(1);
var arrCopy2 = arr.slice(1.4);
var arrCopy3 = arr.slice(1, -2);Arr. Slice (1,4)
var arrCopy4 = arr.slice(-4, -1);Arr. Slice (2,5)
console.log(arr);   //[1, 3, 5, 7, 9, 11]
console.log(arrCopy);   //[3, 5, 7, 9, 11]
console.log(arrCopy2);   / / [3, 5, 7)
console.log(arrCopy3);   / / [3, 5, 7)
console.log(arrCopy4);   / / [5, 7, 9]
Copy the code

8.splice()

Splice () : A powerful array method that can be used in many ways to delete, insert, and replace.

1. Delete the element and return the deleted element

You can delete any number of items by specifying two parameters: the location of the first item to delete and the number of items to delete. For example, splice(0,2) removes the first two items in the array.

var arr = [1.3.5.7.9.11];
var arrRemoved = arr.splice(0.2);
console.log(arr);   / / [5, 7, 9, 11]
console.log(arrRemoved);   / / [1, 3]
Copy the code

2. Add elements to the specified index

You can insert any number of items into the specified location by providing three arguments: the starting location, 0 (number of items to delete), and the item to insert. For example, splice(2,0,4,6) inserts 4 and 6 from position 2 in the current array.

var array1 = [22.3.31.12];
array1.splice(1.0.12.35);  / / []

console.log(array1); // [22, 12, 35, 3, 31, 12]

Copy the code

3. Replace the element at the specified index position

You can insert any number of items into a specified location and delete any number of items simultaneously by specifying three parameters: the starting location, the number of items to delete, and any number of items to insert. The number of inserted items need not be equal to the number of deleted items. For example, splice (2,1,4,6) deletes items at position 2 of the current array, and then inserts 4 and 6 starting at position 2.

const array1 = [22.3.31.12];
array1.splice(1.1.8);   / / [3]

console.log(array1);  // [22, 8, 31, 12]
Copy the code

9. IndexOf () and lastIndexOf ()

Accepts two parameters: the item to look for and, optionally, the index that represents the starting point of the search.

IndexOf () : Searches backwards from the beginning of the array (position 0).

LastIndexOf: Searches forward from the end of the array.

Both methods return the position of the item in the array, or -1 if none is found. The congruence operator is used when comparing the first parameter with each item in the array.

var arr = [1.3.5.7.7.5.3.1];
console.log(arr.indexOf(5));   / / 2
console.log(arr.lastIndexOf(5));   / / 5
console.log(arr.indexOf(5.2));   / / 2
console.log(arr.lastIndexOf(5.4));   / / 2
console.log(arr.indexOf("5"));   / / 1
Copy the code

10.forEach()

ForEach () : Loops through the array, running the given function on each item in the array. This method returns no value. The parameters are of type function and are passed by default.

The parameters are: the contents of the array to traverse; The corresponding array index, the array itself

var arr = [11.22.33.44.55];
arr.forEach(function(x, index, a){
	console.log(x + '|' + index + '|'+ (a === arr)); }); The output is:11|0|true
 22|1|true
 33|2|true
 44|3|true
 55|4|true
Copy the code

11.map()

The map() method returns a new array whose elements are the values processed by the call to the original array element.

The map() method processes the elements in their original array order.

This method does not change the original array

var arr = [1.2.3.4.5];
var arr2 = arr.map(function(item){
	return item*item;
});
console.log(arr2);  //[1, 4, 9, 16, 25]
Copy the code

12.filter()

Filter () : “filter” function. Each item in an array runs a given function and returns an array that meets the filter criteria.

var arr = [1.2.3.4.5.6.7.8.9.10];
var arr2 = arr.filter(function(x, index) {
	return index % 3= = =0 || x >= 8;
});
console.log(arr2);  //[1, 4, 7, 8, 9, 10]
Copy the code

13. The fill () es6 added

The fill() method can fill one or more elements of an array with specific values. When just one parameter is used, the method populates the entire array with the value of that parameter.

let arr = [1.2.3.'cc'.5];
arr.fill(1);
console.log(arr);/ /,1,1,1,1 [1];
Copy the code

If you do not want to change all of the elements in the array, but only some of them, you can use optional start and end position arguments (excluding the element at the end position)

3 parameters: fill value, start position parameter, end position parameter (excluding the element at the end position)

let arr = [1.2.3.'arr'.5];

arr.fill(1.2);
console.log(arr);/ /,2,1,1,1 [1]

arr.fill(0.1.3);
console.log(arr);/ /,0,0,1,1 [1];
Copy the code

14.every()

Every () : checks whether each item in the array meets the condition. True is returned only when all items meet the condition.

var arr = [1.2.3.4.5];
var arr2 = arr.every(function(x) {
	return x < 10;
});
console.log(arr2);  //true
var arr3 = arr.every(function(x) {
	return x < 3;
});
console.log(arr3);  // false
Copy the code

15.some()

Some () : Checks whether there are any items in the array that satisfy the condition, and returns true as long as one item satisfies the condition.

var arr = [1.2.3.4.5];
var arr2 = arr.some(function(x) {
	return x < 3;
});
console.log(arr2);  //true
var arr3 = arr.some(function(x) {
	return x < 1;
});
console.log(arr3);  // false
Copy the code

16. Includes () es7 added

The includes() method is used to determine whether an array contains a specified value, returning true if it does, false otherwise.

The first argument is (mandatory) the value of the element to look up, and the second is (optional) the place to start looking up the element

const array1 = [22.3.31.12.'arr'];
const includes = array1.includes(31);
console.log(includes); // true

const includes1 = array1.includes(31.3); // Start with index 3 to see if 31 exists
console.log(includes1); // false
Copy the code

Note that: includes uses the === operator for value comparisons, with one exception: NaN is considered equal to itself.

let values = [1.NaN.2];
console.log(values.indexOf(NaN));/ / 1
console.log(values.includes(NaN));//true
Copy the code

17. The reduce () and reduceRight ()

Both methods iterate over all the items of the array (that is, the accumulator) and then build a value that is eventually returned.

The reduce() method starts at the first entry of the array and iterates through to the end.

ReduceRight () starts from the last item of the array and traverses forward to the first item.

Four arguments: the previous value, the current value, the index of the item, and the array object

var values = [1.2.3.4.5];
var sum = values.reduceRight(function(prev, cur, index, array){
return prev + cur;
},10);   // The array starts with an initial value of 10 instead of a default value of 0
console.log(sum);  / / 25
Copy the code

18. ToLocaleString () and toString ()

Convert an array to a string

const array1 = [22.3.31.12];
const str = array1.toLocaleString();
const str1 = array1.toString();

console.log(str); / / 22,3,31,12
console.log(str1); / / 22,3,31,12
Copy the code

19. The find () and findIndex ()

The find() and findIndex() methods both take two arguments: a callback function and an optional value that specifies this inside the callback function.

The callback takes three arguments: an element of the array, the index position of that element, and the array itself.

The callback should return true if the given element meets the criteria you defined, and the find() and findIndex() methods both stop the search the first time the callback returns true.

The difference is that the find() method returns the matched value, while findIndex() returns the index of the matched position.

let arr = [1.2.3.'arr'.5.1.9];

console.log(arr.find((value, keys, arr) = > {
    return value > 2;
})); // 3 returns the matching value

console.log(arr.findIndex((value, keys, arr) = > {
    return value > 2;
})); // 2 Returns the index of the matching position
Copy the code

20. CopyWithin () [new in ES6]

The copyWithin() method is used to copy elements from one specified location in the array to another specified location in the array.

This method changes an existing array

// Copy the first two elements to the last two positions in the array
let arr = [1.2.3.'arr'.5];

arr.copyWithin(3.0);
console.log(arr);/ /,2,3,1,2 [1]
Copy the code

By default, the copyWithin() method always copies all the way to the end of the array, but you can also provide an optional argument to limit how many elements are overwritten. This third parameter specifies the location where the replication is stopped (excluding the location itself).

let arr = [1.2.3.'arr'.5.9.17];

// Paste from index 3
// Copy from index 0
// Stop replication when index 3 is encountered
arr.copyWithin(3.0.3);
console.log(arr);/ /,2,3,1,2,3,17 [1]
Copy the code

21. Flat () and flatMap() ES6 are added

The Flat () method recurses through the array of numbers at a specified depth and returns all the elements in a new array combined with the elements in the traversed subarray.

This method returns a new array with no effect on the original data.

Parameter: Specifies the structural depth to extract the nested array, default is 1.

const arr1 = [0.1.2[3.4]].console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]

const arr2 = [0.1.2[[[3.4]]]];

console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]

// Use Infinity to expand nested arrays of any depth
var arr4 = [1.2[3.4[5.6[7.8[9.10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// Flat () flattens the array. If there are empty Spaces in the array, the flat() method skips them
var arr4 = [1.2.4.5];
arr4.flat();
// [1, 2, 4, 5]
Copy the code

The flatMap() method performs a function on each member of the original Array, equivalent to array.prototype.map (), and then flat() on the Array of returned values.

This method returns a new array, leaving the original array unchanged.

// Equivalent to [[2, 4], [3, 6], [4, 8]].flat()
[2.3.4].flatMap((x) = > [x, x * 2])
// [2, 4, 3, 6, 4, 8]
Copy the code

22. Entries (),keys() and values() 【ES6】

Entries (), keys() and values() — For traversing groups of numbers. They both return a traverser object, which can be used for… The of loop iterates

Keys () is traversal of key names, values() is traversal of keys and entries() is traversal of key and value pairs


for (let index of ['a'.'b'].keys()) {  
console.log(index);  
}  
/ / 0
/ / 1
for (let elem of ['a'.'b'].values()) {  
console.log(elem);  
}  
// 'a'  
// 'b'  
for (let [index, elem] of ['a'.'b'].entries()) {  
console.log(index, elem);  
}  
// 0 "a"  
// 1 "b" 
Copy the code

If you don’t use for… The of loop, which can be iterated manually by calling the next method of the iterator object.

let letter = ['a'.'b'.'c'];  
let entries = letter.entries();  
console.log(entries.next().value); // [0, 'a']  
console.log(entries.next().value); // [1, 'b']  
console.log(entries.next().value); // [2, 'c'] 
Copy the code

The resources

Blog.csdn.net/lizhiqiang1…