Create an array

1. Use the Array constructor

const arr1 = new Array(); // Create an empty Array const arr2 = new Array(20); Const arr3 = new Array(" Lily "," Lucy ","Tom"); // Create an Array of 20 const arr3 = new Array(" Lily "," Lucy ","Tom"); // Create an array of three stringsCopy the code

2. Use array literals

const arr4 = []; // Create an empty array const arr5 = [20]; Const arr6 = [" Lily "," Lucy ","Tom"]; // Create an array of 1 const arr6 = [" Lily "," Lucy ","Tom"]; // Create an array of three stringsCopy the code

2. Array methods

0, Array. IsArray ()

Used to determine whether an object is an array. Returns true if the object is an array and false otherwise

const arr=[]
const obj={}
const str=''
console.log(Array.isArray(arr),Array.isArray(obj),Array.isArray(str))	// true,false,false
Copy the code

1. Join () does not change the array

The join() method is used to put all the elements of an array into a single string.

Elements are separated by the specified delimiter. The method accepts only one argument: delimiter (comma by default) If the argument is omitted, the comma is used as the delimiter by default.

Note that the return value is a concatenated string!! The type is string!!

Const arr = [1, 2, 3]; console.log(arr.join('') // 123 console.log(arr.join()); This is equivalent to console.log(arr.join(',')); / / 1, 2, 3. The console log (arr. Join (" - ")); // 1-2-3 console.log(arr); // [1, 2, 3] (original array unchanged) // Empty array console.log([].join()) // "Empty string regardless of delimiterCopy the code

Push () changes the array

Take any number of elements, add them one by one to the end of the array, return the modified array length

const arr = ["a","b","c"]; const item = arr.push("d","e"); console.log(item); // 5 console.log(arr); / / / "a", "b", "c", "d", "e"] / / empty array of the console, log ([]. Push (' a ')) / / 'a'Copy the code

3. Pop () alters the array. If the array is empty, pop() does not alter the array and returns undefined. Deletes the last item at the end of the array and returns the value of the deleted element

const arr = ["a","b","c"]; const item = arr.pop(); console.log(item); // c console.log(arr); / / / "a", "b"] / / empty array of the console, log ([]. Pop ()) / / undefinedCopy the code

Shift () alters the array. If the array is empty, shift() does not alter the array and returns undefined. Deletes the first item of the array and returns the value of the deleted element

const arr = ["a","b","c"]; const item = arr.shift(); console.log(item); // a console.log(arr); / / / "b", "c"] / / empty array of the console, log ([]. Shift ()) / / undefinedCopy the code

5. Unshift () alters the array and returns the length of the array

const arr = ["a","b","c"]; const count = arr.unshift("d","e"); console.log(count); // 5 console.log(arr); //["d", "e", "a", "b", Const testArr=[] console.log(testarr.unshift ('aa')) // 1 console.log(testArr) // aaCopy the code

6, sort() changes the array to sort on it

Syntax: arrayObject.sort(sortby) Sortby Optional. Specify the sort order. It has to be a function.Copy the code

If this method is called without arguments, the elements in the array are sorted alphabetically, or more precisely, by character encoding. To do this, you first convert the elements of the array to strings, if necessary, for comparison.

If you want to sort by other criteria, you need to provide a comparison function that compares two values and then returns a number indicating the relative order of the two values. The comparison function should take two arguments, a and b, and return the following values:

  • If a is less than b, which should precede B in the sorted array, returns a value less than 0.
  • If a is equal to b, 0 is returned.
  • If a is greater than b, return a value greater than 0.

By default, the items are sorted in ascending order, and the toString() transformation method for each item is called when sorting, and the resulting strings are then compared to determine how to sort. Even if every item in the array is a number, the sort() method compares strings, so this happens

const arr1 = ["a", "d", "c", "b"]; console.log(arr1.sort()); // ["a", "b", "c", "d"] const arr2 = [13, 24, 51, 3]; console.log(arr2.sort()); // [13, 24, 3, 51] console.log(arr2); Const arr2 = [13, 24, 51, 3]; const arr2 = [13, 24, 51, 3]; Function (a,b){return b-a} console.log(arr2.sort(function(a,b){return b-a})); // [51, 24, 13, 3] console.log(arr2); // [51, 24, 13, 3] // Empty array const testArr=[] console.log(testarr.sort ()) // [] console.log(testArr) // [] console.log(testArr) //Copy the code

7. Reverse () changes the array

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

const arr = [13, 24, 51, 3]; console.log(arr.reverse()); // [3, 51, 24, 13] console.log(arr); // [3, 51, 24, 13] // Empty array const testArr=[] console.log(testarr.reverse ()) // [] console.log(testArr) // []Copy the code

8. Concat () This method does not alter the existing array, but simply returns a copy of the concatenated array. Concatenate one or more arguments to a copy of the original array. Without arguments, the current array is copied and the copy is returned.

Const arr = hc-positie [1]; Const arrConcat = arr. Concat (9, 11, 13] and {a: 'bb'}); console.log(arrConcat); // [1, 3, 5, 7, 9, 11, 13,{a:'bb'}] console.log(arr); // [1, 3, 5, 7]Copy the code

Slice () does not alter the array and returns a new array of selected elements

Returns a new array of items from the original array specified between the start and end indices

If there is only the first argument, returns all items from the position of that argument to the end (if it is negative, it specifies the position from the end of the array. That is, -1 is the last element, -2 is the penultimate element, and so on.)

If there are two arguments, return the item between the start and end positions (but not the end position; If it is negative, it specifies the position from the end of the array. That is, -1 is the last element, -2 is the penultimate element, and so on.)

Const arr =,3,5,7,9,11 [1]; Console. log(arr.slice()) // [1,3,5,7,9,11] const arrCopy = arr.slice(1); console.log(arrCopy); // [3, 5, 7, 9, 11] const arrCopy2 = arr.slice(1,4); console.log(arrCopy2); // [3, 5, 7] const arrCopy3 = arr.slice(1,-2); console.log(arrCopy3); // [3, 5, 7] const arrCopy4 = arr.slice(-4,-1); console.log(arrCopy4); // [5, 7, 9] Const testArr=[1,2,3,4] console.log(testarr.slice (2)) //[4] console.log(testarr.slice (3)) //[] console.log(testArr.slice(-1)) // [4] console.log(testArr.slice(-1,-2)) // [] console.log(testArr.slice(-2,-1)) //[3] // Const testArr=[] console.log(testarr.slice ()) // [] console.log(testArr) // [] console.log(testArr) // []Copy the code

Splice () changes the original array and returns a new array containing the deleted items (if any). Calling this method on an empty array does not operate and does not return an error

You can delete, insert, and replace array elements

Delete: two arguments: the starting position, the number of items to delete, and the item to insert (empty here). For example, splice(0,2) removes the first two items in the array

Const arr = [1, 2, 3, 4, 5]; Const arrRemoved = arr. Splice (0, 2); console.log(arr); // [3, 4, 5] console.log(arrRemoved); / / [1, 2]Copy the code

Insert: Three arguments: the starting position, the number of items to delete (0 here), and the item to insert. For example, splice(2,0,6,7) inserts 6 and 7 from position 2 in the current array

Const arr = [1, 2, 3, 4, 5]; ,0,6,7 const arrRemoved2 = arr. Splice (2); console.log(arr); // [1, 2, 6, 7, 3, 4, 5] console.log(arrRemoved2); // [] Here, because there are no deleted items, all return values are empty arraysCopy the code

Replace: Three arguments: the starting position, the number of items to delete, and the items to insert. For example, splice (1,1,6,7) deletes the items in the current array position 1, and then inserts 6 and 7 starting at position 1.

Const arr = [1, 2, 3, 4, 5]; ,1,6,7 const arrRemoved3 = arr. Splice (1); console.log(arr); // [1, 6, 7, 3, 4, 5] console.log(arrRemoved3); // [2] There are deleted items, so the value returned is the new array of the replaced deleted itemsCopy the code
The splice() method always returns an array containing the items deleted from the original array, or an empty array if no items were deletedCopy the code

IndexOf () does not alter the array. Returns the indexOf a specified element, or -1 if not found in the array

It takes two arguments: the array element to look for and the starting position (starting at 0 by default), looking from left to right

Const arr =,3,5,7,5,3,1 [1]; console.log(arr.indexOf(5)); / / 2 console. The log (arr. IndexOf (5, 2)); / / 2 console. The log (arr. IndexOf (5, 3)); Log ([].indexof (9)) // -1Copy the code

12, lastIndexOf() does not change the original array, similar to indexOf except that the search method is from right to left

It takes two arguments: the item to look for and the starting position (starting at the end by default), looking from right to left

Const arr =,3,5,7,5,3,1 [1]; console.log(arr.lastIndexOf(5)); / / 4 console. The log (arr. LastIndexOf (5, 4)); / / 4 console. The log (arr. LastIndexOf (5, 3)); / / 2 console. The log (arr. LastIndexOf (5, 2)); / / 2 console. The log (arr. LastIndexOf (5, 1)); / / 1Copy the code

13. ForEach () may alter the array and iterate over it, manipulating elements inside the array

Loops through an array, running the parameter function on each item in the array. The parameters are of function type, where the corresponding parameters are respectively: the contents of the array traversed, the corresponding array index, and the array itself

const arr = ["a", "b", "c"]; arr.forEach(function(x, index,a){ console.log(x,index,a); }); / / a 0 [" a ", "b", "c"] / / b 1 [" a ", "b", "c"] / / c 2 [" a ", "b", "c"] note: return cannot make forEach stop traversalCopy the code

14. Map () does not alter the original array. Instead, it returns a new array whose elements are the values of the original array elements

Refers to a “mapping” of functions that run parameters on each item in an array and return an array of the results of each function call

Note: Map () does not detect empty arrays

const arr = [1, 2, 3, 4, 5]; const arr2 = arr.map(function(x){ return x*x; }); console.log(arr2); // [1, 4, 9, 16, 25Copy the code
Const arr1=[1,2,3,4,5,6] const arr2=[3,4,5] # map return arr2.includes(item) }) console.log(arr3) // [false,false,true,true,true,false] const arr4=arr1.map(item=>{ return Item <3}) console.log(arr4) // [true, true, false, false, false, false] Const arr5=arr1.filter(item =>{return arr2.includes(item)}) console.log(arr5) // [3, 4, 5]Copy the code

15. Filter () does not alter the original array and returns a new array that satisfies the filter criteria

The filter() method creates a new array of elements by checking all eligible elements in the specified array.

Note: Filter () does not detect an empty array

Const arr = [1, 2, 3, 4, 5]; const arr = [1, 2, 3, 4, 5]; const arr2 = arr.filter(function(x, index) { return x > 3 || index < 2; }); console.log(arr2); // [1, 2, 4, 5]Copy the code

16, every() does not change the array and returns true or false

Check whether each item in the array satisfies the condition, and return true only if all items satisfy the condition.

Note: every() does not check for empty arrays

const arr = [1, 2, 3, 4, 5]; const arr2 = arr.every(function(x) { return x < 10; }); console.log(arr2); // true const arr3 = arr.every(function(x) { return x < 3; }); console.log(arr3); // false // Empty array every does not detect empty arraysCopy the code

17. Some () does not alter the array

Checks if there are any items in the array that satisfy the condition, and returns true if any of the items satisfy the condition.

Note: Empty arrays are not detected

const arr = [1, 2, 3, 4, 5];
const arr2 = arr.some(function(x) {
return x < 3;
});
console.log(arr2);  // true
const arr3 = arr.some(function(x) {
return x < 1;
});
console.log(arr3);  // false
Copy the code

Reduce () does not perform callbacks on empty arrays

Implement iterating through all of the items in the array, and then building a value that is ultimately returned. Reduce () takes two arguments: the function called on each item, as the initial value of the merge basis. Const values = [1,2,3,4,5]; const values = [1,2,3,4,5]; const sum = values.reduce(function(prev, x, index, array){ return prev + x; }, 10); console.log(sum); / / 25Copy the code

19 and reduceRight ()

Same as reduce(), but traversal is from right to left, the reverse of reduce()

ValueOf () does not alter the original array

The valueOf() method returns the original Array value

const arr=['aa','bb','cc']
console.log(arr.valueOf())   // ['aa','bb','cc']
console.log(arr)						//  ['aa','bb','cc']
Copy the code

21. ToString () does not alter the original array

The toString() method converts an array to a string and returns a comma-concatenated string!! The type is string!!

Const arr=[1,2,3,4,5] const arr1= arr.tostring () console.log(arr1,arr) // '1,2,3,4,5' console.log(arr2.toString()) // ''Copy the code

22, Array.from() returns a real Array

The array.from () method converts an array-like object or traversable object into a real Array. So what is an array-like object? The basic requirement for an array-like object is an object with a length attribute.

22.1. Convert an array-like object into a real array:

Let arrayLike = {0: 'Tom', 1: '65', 2: 'male', 3: [' Jane ', 'John', 'Mary'], 'length' : 4} let arr = Array. The from (arrayLike) console. The log (arr) / / [' Tom ', '65', 'male' [' Jane ', 'John', 'Mary']] let arrayLike2 = {' 0 ': 'a', '1': 'b', '2': 'c', length: 3 }; Var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c'] // let arr2 = array. from(arrayLike); // ['a', 'b', 'c']Copy the code

So, if you remove the length attribute from the code above, you return an empty array of length 0. As follows:

Const arrLike={0:'a',1:'b',2:'c'} console.log(array. from(arrLike)) // [] However, data against set structures can be converted directly to arrays, eg: Const arr=['a','b','c','d'] const setArr=new Set(arr)/print  Set(4) {"a", "b", "c", "d"} console.log(Array.from(setArr)) // ['a','b','c','d']Copy the code

The object has a length attribute, but instead of a numeric attribute, the object has a string name, as follows:

Let arrayLike = {' name ':' Tom ', 'age', '65', 'sex' : 'male', 'friends' : [' Jane', 'John', 'Mary'], length: 4 } let arr = Array.from(arrayLike) console.log(arr) // [ undefined, undefined, undefined, Undefined] # only length attribute object let arrayLike = {length: 4 } let arr = Array.from(arrayLike) console.log(arr) // [ undefined, undefined, undefined, undefined ]Copy the code

The result is an array of length 4 with undefined elements

Thus, to convert an array-like object into a true array, the following conditions must be met:

1. This class of array objects must have a length attribute, which specifies the length of the array. If there is no length attribute, the transformed array is an empty array.

2. The property name of this array object must be a numeric or string number

Ps: The property names of this array object can be quoted or unquoted

22.2. Convert Set data into a real array:

,45,97,9797,564,134,45642 let arr = [12] let the set = new set (arr) console. The log (set). / / the console log (Array) from (set)) / / [12, 45, 97, 9797, 564, 134, 45642]Copy the code

Array.from can also take a second argument, similar to the map method of arrays, that is used to process each element and place the value in the returned Array. As follows:

,45,97,9797,564,134,45642 let arr = [12] let the set = new set (arr) console. The log (Array) from (the set of item = > item + 1)) / / [13, 46, 98, 9798, 565, 135, 45643]Copy the code

22.3 Converting a string to an array

let str = 'hello world! '; console.log(Array.from(str)) // ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]Copy the code

The array. from argument is a real Array:

The console. The log (Array. The from (,45,47,56,213,4654,154 [12])) / /,45,47,56,213,4654,154 [12]Copy the code

In this case, array. from returns a new Array that looks exactly like it

23, an Array of ()

Used to convert a set of values into an array.

Array of (3, 11, 8) / / [3, 11, 8] Array of (3) / / [3] and Array () the behavior of different Array (3, 11, 8) / / [8] 3, 11, Array (3) / / /,, ,] ----Array(3) creates an Array of three lengths and each element is undefined. Array is the same as new ArrayCopy the code

24. Find () does not alter the original array

Note: For an empty array, the function is not executed

Use to find the first member of the array that matches the criteria. Its argument is a callback function that is executed by all array members until the first member that returns true is found, and then returned. If there is no qualified member, undefined is returned

[1, 5, 10, 15].find(function(value, index, arr) { return value > 9; }) / / 10Copy the code

25. FindIndex () does not alter the array

Note: For an empty array, the function is not executed

The usage is very similar to find, returning the position of the first qualified array member, or -1 if all members fail.

[1, 5, 10, 15].findIndex(function(value, index, arr) { return value > 9; / / 2})Copy the code

26. Fill () changes the original array and returns the changed array

Fills an array with the given value

Note: An empty array is not executed

['a', 'b', 'c'].fill(7) // [7, 7, 7]. ['a', 'b', 'c']. Fill (7, 1, 2) // ['a', 7, 'c']. Fill starts at index 1, fills 7 into the original array, and ends before index 2Copy the code

27, includes ()

Syntax: arr.includes(searchElement) searchElement: mandatory. The value of the element to look up. Arr. includes(searchElement, fromIndex) fromIndex: optional. The search for searchElement starts at that index. If it is negative, the search starts from the index of array.length + fromIndex in ascending order. The default is 0. Return false if fromIndex is greater than or equal to the array length. Const arr = ['a', 'b', 'c']; arr.includes('c', 3); //false arr.includes('c', 100); // False evaluates to an index less than 0. If fromIndex is negative, the calculated index will be used as the place to start the searchElement search. If the calculated index is less than 0, the entire array is searched. // Array length is 3 // fromIndex is -100 // computed Index is 3 + (-100) = -97 const arr = [' A ', 'b', 'c']; arr.includes('a', -100); // true arr.includes('b', -100); // true arr.includes('c', -100); // trueCopy the code

Checks whether the array contains the given value, returning a Boolean value

[1, 2, 3].includes(2); // true [1, 2, 3].includes(4); // false [1, 2, NaN].includes(NaN); // true The second argument indicates the starting location of the search (default: 0). // false [1, 2, 3].includes(3, -1); // trueCopy the code

Iii. Remaining Problems:

1. Which methods change the original array and which methods return a new array?

2. What is the difference between map and Filter when returning?

3. How do these methods perform if the array is empty?