1. Common looping methods for arrays
1.1 some
// Syntax: item: current element, index: current index, arr: source array
Array.some((item,index,arr) = > item%2= = =0 )
Copy the code
-
Return true as long as one member passes
-
Some () — find a valid one — return true– do not continue the loop (as opposed to every())
let arr=[1.2.3.4.5] let res=arr.some((item,index,arr) = >item%2= = =0) console.log(res)//true Copy the code
1.2 every
// Syntax: item: current element, index: current index, arr: source array
Array.every((item,index,arr) = > item%2= = =0 )
Copy the code
-
Return true if all members pass
-
Every ()– iterates the array, — finds the unqualified — returns false—- does not continue iterating the array (as opposed to some)
let arr=[1.2.3.4.5] let res=arr.every((item,index,arr) = >item%2= = =0) console.log(res)//false Copy the code
1.3 Map
// Syntax: item: current element, index: current index, arr: source array, this: point to
Array.forEach((item,index,arr) = >item,this)
Copy the code
-
Collect the value of return and form a new array (map to a new array based on the source data)
let arr = [1.2.3.4] let outArr= arr.map(item= >item*2) console.log(outArr); / /,4,6,8 [2] Copy the code
1.4 Filter
// Syntax: : item: current element, index: current index, arr: source array, this: point to
Array.filter((item,index,arr) = >item>1.this)
Copy the code
-
Collect values that return true and form a new array
let arr = [1.undefined.3.null.0.' '.false.NaN] let outArr= arr.filter(item= >item! =undefined) console.log(outArr);/ / [1,3,0, ' ', false, NaN] Copy the code
Note that only null==undefined (undefined=== uninitialized)
1.5 Reduce (accumulator)
-
The function that executes each value in the array (except the first value if no initialValue is provided), with four arguments:
- Parameter 1: Accumulator (ACC)
- Parameter 2: Current Value (CUR)
- Current index (IDx)
- Source Array(SRC)
-
The initialValue optional
- As the first call
callback
The value of the first argument to the function. If no initial value is provided, the first element in the array is used.Calling reduce on an empty array with no initial value will report an error.
- As the first call
[0.1.2.3.4].reduce(function(accumulator, currentValue, currentIndex, array){
return accumulator + currentValue;
},0);
Copy the code
-
Reduce instance: Finds the sum of all the values of an array
var sum = [0.1.2.3].reduce(function (accumulator, currentValue) { return accumulator + currentValue; }, 0); / / and is 6 Copy the code
-
Reduce instance: Classifies objects by attribute
var people = [ { name: 'Alice'.age: 21 }, { name: 'Max'.age: 20 }, { name: 'Jane'.age: 20}];function groupBy(objectArray, property) { return objectArray.reduce(function (acc, obj) { var key = obj[property]; if(! acc[key]) { acc[key] = []; } acc[key].push(obj);return acc; }, {}); } var groupedPeople = groupBy(people, 'age'); // groupedPeople is: / / { / / 20: // { name: 'Max', age: 20 }, // { name: 'Jane', age: 20 } / /, // 21: [{ name: 'Alice', age: 21 }] // } Copy the code
1.6 the forEach
// Syntax: item: current element, index: current index, arr: source array, this: point to
Array.forEach((item,index,arr) = >{},this)
Copy the code
-
No return value
let arr=[1.2.3.4] console.log(arr.forEach(item= > 1));//undefined Copy the code
-
Second argument: this (not often used)
// Use arrow functions instead let arr = [1.2.3.4] let outArr=[] arr.forEach(function(item){ this.push(item) }, outArr) console.log(outArr);/ / [1, 2, 3, 4] Copy the code
-
ForEach cannot use backs to break loops
let arr = [1.2.3.4] arr.forEach(item= >{ if(item===2) {break //Uncaught SyntaxError: Illegal break statement / / the continue: in the same way}})console.log(arr); Copy the code
-
Does not print if the value of the array is null
let arr = [1.3.4] arr.forEach(item= >console.log(item)) / / 134 Copy the code
2. Stack methods for arrays
2.1 POP (Delete)
/ / grammar arr. Pop ()
Copy the code
-
Removes the last element from the array and returns the value of that element. This method changes the length of the array.
const plants = ['broccoli'.'cauliflower'.'cabbage'.'kale'.'tomato']; console.log(plants.pop());// 'tomato' console.log(plants); //["broccoli", "cauliflower", "cabbage", "kale"] Copy the code
2.2 Push (Add)
/ / grammar arr. Push (item1, item2,...).
Copy the code
-
Starts at the end of the array and returns the new length of the array.
const animals = ['pigs'.'goats'.'sheep']; const count = animals.push('cows'); console.log(count);/ / 4 console.log(animals); // ["pigs", "goats", "sheep", "cows"] Copy the code
2.3 Shift (Delete)
/ / grammar arr. The shift ()
Copy the code
-
Use to delete the first element of an array and return the deleted element. This method changes the length of the array.
const array1 = [1.2.3]; const firstElement = array1.shift(); console.log(firstElement);// 1 console.log(array1);/ / [2, 3] Copy the code
2.4 Unshift (Add)
/ / grammar arr. Unshift (item1, item2,...).
Copy the code
-
Use to add one or more elements to the beginning of an array and return the new length of the array
const array1 = [1.2.3]; console.log(array1.unshift(4.5));/ / 5 console.log(array1);//[4, 5, 1, 2, 3] Copy the code
3. Array splicing
3.1 the join
// syntax separator: separator
arr.join("separator")
Copy the code
-
What delimiter is used to concatenate all the elements of an array into a string and return the string
const elements = ['Fire'.'Air'.'Water']; console.log(elements.join());//"Fire,Air,Water" console.log(elements.join(' '));//"FireAirWater" console.log(elements.join(The '-'));//"Fire-Air-Water" Copy the code
3.2 the concat
// let arrs=arr1.concat(arr2)
Copy the code
-
Used to merge two or more arrays. This method does not change an existing array, but returns a new array
const array1 = ['a'.'b'.'c']; const array2 = ['d'.'e'.'f']; const array3 = array1.concat(array2); console.log(array3); // expected output: Array ["a", "b", "c", "d", "e", "f"] Copy the code
-
Note the use of Es6 extension operators […arr1,… arR2]
4. Array deletion method
4.1 slice
// Syntax begin: start position end: end position [) Close left and open right
arr.slice(begin,end)
Copy the code
-
Returns a new array. Shallow copy of the array determined by begin and end (begin, but not end). The original array will not be changed.
var fruits = ['Banana'.'Orange'.'Lemon'.'Apple'.'Mango']; var citrus = fruits.slice(1.3); console.log(citrus); //["Orange","Lemon"] console.log(fruits); //['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] Copy the code
4.2 splice
// Syntax start: specifies the starting position for deleting or adding elements. DeleteCount: specifies the number of elements to be deleted. Item: Specifies the elements to be added from start
arr.splice(start,deleteCount,item1,item2)
Copy the code
-
Delete or add elements to modify the source array, returning the modified contents. This method changes the original array
- add
var myFish = ["angel"."clown"."mandarin"."sturgeon"]; var removed = myFish.splice(2.0."drum"); console.log(removed)/ / [] console.log(myFish)// ["angel", "clown", "drum", "mandarin", "sturgeon"] Copy the code
- replace
var myFish = ["angel"."clown"."mandarin"."sturgeon"]; var removed = myFish.splice(2.1."drum"); console.log(removed)//["mandarin"] console.log(myFish)// ["angel", "clown", "drum", "sturgeon"] Copy the code
- delete
var myFish = ["angel"."clown"."mandarin"."sturgeon"]; var removed = myFish.splice(2.1); console.log(removed)//["mandarin"] console.log(myFish)// ["angel", "clown", "sturgeon"] Copy the code
5. Array search index method
5.1 indexOf
// Syntax searchValue: the element to be searched fromIndex: the position to start the search from left to right
arr.indexOf(searchValue,fromIndex)
Copy the code
-
Returns the index of the first occurrence of the specified value, or -1 if not found
var array = [2.5.9]; array.indexOf(2); / / 0 array.indexOf(7); // -1 array.indexOf(9.2); / / 2 array.indexOf(2, -1); // -1 array.indexOf(2, -3); / / 0 Copy the code
5.2 lastIndexOf
// syntax searchValue: the string value to be searched fromIndex: the position where the search starts is searched from right to left (the index is still counted from left to right starting with 0)
arr.lastIndexOf(searchValue,fromIndex)
Copy the code
-
Returns the index of the last occurrence of the specified value, or -1 if not found
// Case sensitive var array = [2.5.9.2]; var index = array.lastIndexOf(2); // index is 3 index = array.lastIndexOf(7); // index is -1 Copy the code
5.3 includes
FromIndex: Searches from the fromIndex index
arr.includes(valueToFind,fromIndex )
Copy the code
-
Returns true if the array contains a specified value, false otherwise
Note that using includes() to compare strings and characters is case sensitive.
[1.2.3].includes(2); // true [1.2.3].includes(4); // false [1.2.3].includes(3.3); // false // if fromIndex is greater than the length of the array, return false [1.2.3].includes(3, -1); // true [1.2.NaN].includes(NaN); // true Copy the code
5.4 the find
// Syntax item: current element, index: current index, arr: source array, this: point to
arr.find((item,index,arr) = >item>2)
Copy the code
-
The value that iterates through the array to find the first eligible member, or returns undefined if none is found
let ary = [{ id: 1.name: 'Joe' }, { id: 2.name: 'bill' }]; let target = ary.find((item, index) = > item.id == 2);// Select a value from the array whose element id is 2 Copy the code
const array1 = [5.12.8.130.44]; const found = array1.find(element= > element > 10); console.log(found);/ / 12 Copy the code
5.5 findIndex
// Syntax item: current element, index: current index, arr: source array, this: point to
arr.findIndex((item,index,arr) = >item>3)
Copy the code
-
The index that iterates through the array to find the first eligible array member, or -1 if none is found
let ary = [1.5.10.15]; let index = ary.findIndex((value, index) = > value > 9); console.log(index); / / 2 Copy the code
Summary: Find the index of an array member that meets the criteria. If no index is found, return -1
6. Sort arrays
6.1 the sort
// Syntax: firstE1 the first element to compare secondE2 the second element to compare
Array.sort((firstE1,secondE2) = >firstE1-secondE2)
Copy the code
-
Sort the elements of an array and return an array. Note that the array is sorted in place and is not copied
// The following is the ascending order let numbers = [4.2.5.1.3]; numbers.sort((a, b) = > a - b); console.log(numbers); // [1, 2, 3, 4, 5] // The following is in descending order let numbers = [4.2.5.1.3]; numbers.sort((a, b) = > b - a); console.log(numbers); // [5, 4, 3, 2, 1] Copy the code
6.2 reverse
/ / grammar arr. Reverse ()
Copy the code
-
Method reverses the position of the elements in an array and returns the array
a.reverse(); console.log(a); / / [3, 2, 1) Copy the code
6.3 Random Sorting
function compate(){
return Math.random()-0.5;
}
arr.sort(compate())
Copy the code
7. Convert pseudo-arrays to real arrays
7.1 the from
// arrayLike: a pseudo-array object or iterable that you want to convert to an array. MapFn: If specified, each element in the new array will execute the callback function.
ArrayThe from (arrayLike mapFn)Copy the code
-
Creates a new, shallow-copy instance of a pseudo-array or iterable.
console.log(Array.from('foo')); // expected output: Array ["f", "o", "o"] console.log(Array.from([1.2.3].x= > x + x)); // expected output: Array [2, 4, 6] Copy the code
8. Check arrays
8.1 isArray
// The value that the syntax obj needs to check
Array.isArray(obj)
Copy the code
- Used to determine whether the value passed is an Array
// The following function calls all return true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array('a'.'b'.'c'.'d'))
// Little-known fact: array. prototype is an Array.
Array.isArray(Array.prototype);
// The following function calls all return false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray('Array');
Array.isArray(true);
Array.isArray(false);
Array.isArray(new Uint8Array(32))
Array.isArray({ __proto__: Array.prototype }); console.log(Array.isArray([1."Flowers,"."hs"])// The following function calls all return truearRay.isarray ([]); Array.isArray([1]); Array.isArray(new Array()); Array.isarray (new Array('a', 'b', 'c', 'd'))// Array.isArray(Array.prototype); // The following function calls all return falsearray.isarray (); Array.isArray({}); Array.isArray(null); Array.isArray(undefined); Array.isArray(17); Array.isArray('Array'); Array.isArray(true); Array.isArray(false); Array.isArray(new Uint8Array(32))Array.isArray({ __proto__: Array.prototype }); ray.isArray(9)); //false
Copy the code