preface
In the development, there are many usage scenarios for arrays. On weekdays, many array APIs / related operations are also involved. This content has not been sorted out and summarized. Many times, even if you have used this api several times, it is easy to forget in the development. You still need to Google. Therefore, I hope to have a systematic summary of this content. Under this background, there is this article. If you like, you can praise / pay attention to it and support it. I hope you can gain something after reading this article.
Front end advanced accumulation,official account,GitHub
This article is a long one. It is recommended that you like it and save it for later reading.
Create an array:
// Literal method: // This method is also the most commonly used, which is quite convenient when initializing the array var a = [3, 11, 8]; // [3,11,8]; // Constructor: // In fact, new Array === Array, adding or not adding new has no effect at all. var a = Array(); // [] var a = Array(3); // [,,] var a = Array(3,11,8); // [ 3,11,8 ] Copy code
ES6 Array.of() returns an array of all parameter values
Definition: returns an array of all parameter values. If there are no parameters, an empty array is returned.
Purpose: array The purpose of of () is to solve the problem that the behavior of the above constructor is different due to the different number of parameters.
let a = Array.of(3, 11, 8); // [3,11,8] let a = Array.of(3); // [3] Copy code
ES6 Arrary.from() turns the two types of objects into real arrays
Definition: used to convert two types of objects into real arrays (return a new array without changing the original object).
Parameters:
First argument (required): the object to convert to a real array.
The second parameter (optional): an array like map method, which processes each element and puts the processed value into the returned array.
The third parameter (optional): used to bind this.
// 1. The object has the length attribute 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','o'] let arr = Array.from(new Set(['a','b'])); // ['a','b'] Copy code
method:
The array prototype provides many methods, which are divided into three categories: one will change the value of the original array, the other will not change the original array, and the traversal method of the array.
Methods to change the original array (9):
let a = [1,2,3]; ES5: a.splice()/ a.sort() / a.pop()/ a.shift()/ a.push()/ a.unshift()/ a.reverse() ES6: a.copyWithin() / a.fill Copy code
For these methods that can change the original array, pay attention to avoid changing the options of the original array in circular traversal, such as changing the length of the array, resulting in problems in the length of traversal.
splice() add / remove array elements
Definition: the splice() method adds / deletes items to / from the array, and then returns the deleted items
Syntax: array splice(index,howmany,item1,.....,itemX)
Parameters:
- index: required. Integer that specifies the position of the item to be added / deleted. Use a negative number to specify the position from the end of the array.
- howmany: optional. Number of items to delete. If set to 0, the item is not deleted.
- item1, ..., itemX: optional. Adds a new item to the array.
Return value: if any element is deleted, a new array containing the deleted item is returned.
eg1: delete element
let a = [1, 2, 3, 4, 5, 6, 7]; let item = a.splice(0, 3); // [1,2,3] console.log(a); // [4,5,6,7] // Delete 3 elements starting with array subscript 0 let item = a.splice(-1, 3); // [7] // Three elements are deleted from the last element, and only 7 are deleted because of the last element Copy code
eg2: delete and add
let a = [1, 2, 3, 4, 5, 6, 7]; let item = a.splice(0,3,'add to'); // [1,2,3] console.log(a); // ['Add', 4,5,6,7] // Starting from the array subscript 0, delete 3 elements and add the element 'Add' let b = [1, 2, 3, 4, 5, 6, 7]; let item = b.splice(-2,3,'Add 1','Add 2'); // [6,7] console.log(b); // [1,2,3,4,5, 'add 1', 'add 2'] // Starting from the last and second element of the array, delete three elements and add two elements' add 1 'and' add 2 ' Copy code
eg3: do not delete, only add:
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 b = [1, 2, 3, 4, 5, 6, 7]; let item = b.splice(-1,0,'Add 1','Add 2'); // [] no element deleted, return empty array console.log(b); // [1,2,3,4,5,6, 'add 1', 'add 2', 7] add two elements before the last element Copy code
From the above three chestnuts:
- If there are not enough elements in the array, it will be deleted until the last element
- The element of the operation, including the element at the beginning
- Many elements can be added
- Add is added before the starting element
-
vue delete
this.a = ['222','333']; this.a.$remove('222');
sort() array sort
Definition: the sort() method sorts the array elements and returns the array.
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 element is not a string, the toString() method will be called to convert the element into the Unicode (universal code) site of the string, and then compare the characters.
// The string arrangement looks normal var a = ["Banana", "Orange", "Apple", "Mango"]; a.sort(); // ["Apple","Banana","Mango","Orange"] // When sorting numbers, because after being converted to Unicode strings, some numbers will be ranked later, which is obviously not what we want var a = [10, 1, 3, 20,25,8]; console.log(a.sort()) // [1,10,20,25,3,8]; Copy code
Two parameters of the comparison 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;
For the deeper internal implementation and processing mechanism of sort() method, you can take a look at this article Learn more about the sort method of javascript
sort common usage:
-
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 = [{id:10,age:2},{id:5,age:4},{id:6,age:10},{id:9,age:6},{id:2,age:8},{id:10,age:9}]; array.sort(function(a,b){ if(a.id === b.id){// If the values of id are equal, the values of age are in descending order return b.age - a.age }else{ // If the values of IDS are not equal, the values of IDS are in ascending order return a.id - b.id } }) // [{"id":2,"age":8},{"id":5,"age":4},{"id":6,"age":10},{"id":9,"age":6},{"id":10,"age":9},{"id":10,"age":2}] Copy code
-
Custom comparison function, the sky is your limit
Similar: using the return value, we can write any comparison function that meets our needs
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
pop() deletes the last element in an array
Definition: the pop() method deletes the last element in an array and returns this element.
Parameter: none.
let a = [1,2,3]; let item = a.pop(); // 3 console.log(a); // [1,2] Copy code
shift() deletes the first element of the array
Definition: the shift() method deletes the first element of the array and returns this element.
Parameter: none.
let a = [1,2,3]; let item = a.shift(); // 1 console.log(a); // [2,3] Copy code
push() adds an element to the end of the array
Definition: the push() method adds one or more elements to the end of the array and returns a new length.
Parameters: Item1, Item2, Itemx, the element to be added to the end of the array
let a = [1,2,3]; let item = a.push('end'); // 4 console.log(a); // [1,2,3, 'end'] Copy code
unshift()
Definition: the unshift() method adds one or more elements to the beginning of the array and returns a new length.
Parameters: Item1, Item2, Itemx, the element to be added to the beginning of the array
let a = [1,2,3]; let item = a.unshift('start'); // 4 console.log(a); // ['start', 1,2,3] Copy code
reverse() reverses the order of the elements in the array
Definition: the reverse() method is used to reverse the order of the elements in the array.
Parameter: None
let a = [1,2,3]; a.reverse(); console.log(a); // [3,2,1] Copy code
ES6: copyWithin() copies members from the specified location to another location
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) Copy code
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
eg:
// -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 chestnuts:
- 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
ES6: fill() to fill array
Definition: fills an array with the given value.
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 this length
['a', 'b', 'c'].fill(7) // [7, 7, 7] ['a', 'b', 'c'].fill(7, 1, 2) // ['a', 7, 'c'] Copy code
Methods without changing the original array (8):
ES5: slice,join,toLocateString,toStrigin,cancat,indexOf,lastIndexOf, ES7: includes Copy code
slice() shallow copies the elements of the array
Definition: the method returns a shallow copy of a selected array from start to end (excluding end) to a new array object, and the original array will not be modified.
Note: the string also has a slice() method to extract the string. Don't confuse it.
Syntax:
array.slice(begin, end); Copy code
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.
join() array to string
Definition: 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.
Syntax:
array.join(str) Copy code
Parameters:
Str (optional): Specifies the delimiter to use. By default, comma is used as the delimiter.
let a= ['hello','world']; let str=a.join(); // 'hello,world' 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. Object to string is recommended stringify(obj); Copy code
Therefore, 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.
toLocaleString() array to string
Definition: 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.
Syntax:
array.toLocaleString() Copy code
Parameter: none.
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.
toString() array to string is not recommended
Definition: the toString() method converts an array into a comma linked string.
Syntax:
array.toString() Copy code
Parameter: none.
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.
It is worth noting that js will call this method to automatically convert the array into a string when the array and string are operated
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
cancat
Definition: method is used to merge two or more arrays and return a new array.
Syntax:
var newArr =oldArray.concat(arrayX,arrayX,......,arrayX) Copy code
Parameters:
arrayX (required): this parameter can be a concrete value or an array object. It can be any number.
eg1:
let a = [1, 2, 3]; let b = [4, 5, 6]; //Join two arrays let newVal=a.concat(b); // [1,2,3,4,5,6] // Join three arrays let c = [7, 8, 9] let newVal2 = a.concat(b, c); // [1,2,3,4,5,6,7,8,9] // Add element let newVal3 = a.concat('Add element',b, c,'Add another one'); // [1,2,3, "add element", 4,5,6,7,8,9, "add another"] // Merging nested arrays copies nested arrays let d = [1,2 ]; let f = [3,[4]]; let newVal4 = d.concat(f); // [1,2,3,[4]] Copy code
ES6 extended operator Merge arrays:
Because the syntax of ES6 is more concise and easy to understand, I mostly use To deal with Operator can realize each chestnut of cancat, which is more concise and has the effect of highly customizing the position of array elements.
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
For more details on the extender, move to Ruan Yifeng's great God ECMAScript 6 getting started
indexOf() finds whether an element exists in the array and returns the subscript
Definition: returns the first index of a given element that can be found in the array. If it does not exist, it returns - 1.
Syntax:
array.indexOf(searchElement,fromIndex) Copy code
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
eg:
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
Usage scenario:
- Array de duplication
- Perform operations according to the obtained array subscript, change the value in the array, etc.
- Judge whether it exists and execute the operation.
lastIndexOf() finds the last position of the specified element in the array
Definition: the 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)
Syntax:
arr.lastIndexOf(searchElement,fromIndex) Copy code
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
ES7 includes() finds whether the array contains an element and returns a Boolean
Definition: returns a Boolean value indicating whether an array contains a given value
Syntax:
array.includes(searchElement,fromIndex=0) Copy code
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
eg:
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
Compatibility (MDN): Chrome 47, Firefox 43, edge 14, opera 34, Safari 9, ie are not implemented.
Traversal methods (12):
js does not change the original array. There are 12 methods in total:
ES5: forEach,every ,some, filter,map,reduce,reduceRight, ES6: find,findIndex,keys,values,entries Copy code
About traversal:
- On the efficiency of traversal, you can take a look at this article Detailed JS traversal
- Try not to modify the values to be traversed later during traversal
- Try not to modify the length of the array (delete / add) during traversal
forEach
Definition: executes a callback function for each item in the array that contains valid values in ascending order.
Syntax:
array.forEach(function(currentValue, index, arr), thisValue) Copy code
Parameters:
Function: the function to be called for each element in the array.
// Parameters of callback function 1. currentValue(must),The value of the current element of the array 2. index(Optional), Index value of the current element 3. arr(Optional),Array object itself Copy code
Thisvalue (optional): the value of this bound object when the callback function is executed. The default value is undefined
About forEach(), you should know:
- You cannot exit the loop halfway. You can only use return to exit this callback for the next callback.
- It always returns an undefined value, even if you return a value.
The following similar syntax also applies to these rules
1. For an empty array, the callback function will not be executed 2. For elements that have been deleted during the iteration, or empty elements, the callback function is skipped 3. The number of traversals will be determined before the first cycle, and the elements added to the array will not be traversed. 4. If the existing value is changed, it is passed to callback The value of is the value traversed to their moment. Copy code
eg:
let a = [1, 2, ,3]; // Finally, the second element is empty and will not be traversed (undefined and null will be traversed) let obj = { name: 'OBKoro1' }; let result = a.forEach(function (value, index, array) { a[3] = 'Change element'; a.push('It is added to the tail end and will not be traversed') console.log(value, 'forEach First parameter passed'); // Print 1 and 2 respectively and change the elements console.log(this.name); // OBKoro1 prints this three times and binds it to the obj object // break; // break will report an error return value; // return can only end this callback. The next callback will be executed console.log('Not because return The next circular callback is executed') }, obj); console.log(result); // return undefined even if it returns a value // Callback functions also accept connector function writing Copy code
every checks whether all elements of the array meet the judgment conditions
Definition: this method is used to detect whether all elements of the array meet the conditions defined by the function
Syntax:
array.every(function(currentValue, index, arr), thisValue) Copy code
Parameters: (the parameters and syntax of these methods are similar)
Function: the function to be called for each element in the array.
// Parameters of callback function 1. currentValue(must),The value of the current element of the array 2. index(Optional), Index value of the current element 3. arr(Optional),Array object itself Copy code
Thisvalue (optional): the value of this bound object when the callback function is executed. The default value is undefined
Method return value rule:
- If an element in the array is detected to be unsatisfactory, the entire expression returns false and the remaining elements will not be detected.
- Returns true if all elements meet the criteria=
eg:
function isBigEnough(element, index, array) { return element >= 10; // Determine whether all elements in the array are greater than 10 } let result = [12, 5, 8, 130, 44].every(isBigEnough); // false let result = [12, 54, 18, 130, 44].every(isBigEnough); // true // Accept arrow function writing [12, 5, 8, 130, 44].every(x => x >= 10); // false [12, 54, 18, 130, 44].every(x => x >= 10); // true Copy code
Whether there are elements in some array that meet the judgment conditions
Definition: whether there are elements in the array that meet the judgment conditions
Syntax:
array.some(function(currentValue, index, arr), thisValue) Copy code
Parameters: (the parameters and syntax of these methods are similar)
Function: the function to be called for each element in the array.
// Parameters of callback function 1. currentValue(must),The value of the current element of the array 2. index(Optional), Index value of the current element 3. arr(Optional),Array object itself Copy code
Thisvalue (optional): the value of this bound object when the callback function is executed. The default value is undefined
Method return value rule:
-
If one element satisfies the condition, the expression returns true and the remaining elements will not be detected.
-
If there is no element that meets the condition, false is returned.
function isBigEnough(element, index, array) { return (element >= 10); //Is there an element greater than 10 in the array } let result = [2, 5, 8, 1, 4].some(isBigEnough); // false let result = [12, 5, 8, 1, 4].some(isBigEnough); // true Copy code
filter filters the original array and returns a new array
Definition: returns a new array containing all the elements of the test implemented by the provided function.
Syntax:
let new_array = arr.filter(function(currentValue, index, arr), thisArg) Copy code
Parameters: (the parameters and syntax of these methods are similar)
Function: the function to be called for each element in the array.
// Parameters of callback function 1. currentValue(must),The value of the current element of the array 2. index(Optional), Index value of the current element 3. arr(Optional),Array object itself Copy code
Thisvalue (optional): the value of this bound object when the callback function is executed. The default value is undefined
eg:
let a = [32, 33, 16, 40]; let result = a.filter(function (value, index, array) { return value >= 18; // Returns all elements greater than 18 in the a array }); console.log(result,a);// [32,33,40] [32,33,16,40] Copy code
map processes each element in the array and returns a new array
Definition: creates a new array. The result is the result returned after each element in the array calls a provided function.
Syntax:
let new_array = arr.map(function(currentValue, index, arr), thisArg) Copy code
Parameters: (the parameters and syntax of these methods are similar)
Function: the function to be called for each element in the array.
// Parameters of callback function 1. currentValue(must),The value of the current element of the array 2. index(Optional), Index value of the current element 3. arr(Optional),Array object itself Copy code
Thisvalue (optional): the value of this bound object when the callback function is executed. The default value is undefined
eg:
let a = ['1','2','3','4']; let result = a.map(function (value, index, array) { return value + 'New element of new array' }); console.log(result, a); // ["1 new element of new array", "2 new element of new array", "3 new element of new array", "4 new element of new array"] ["1", "2", "3", "4"] Copy code
reduce provides an accumulator for the array and combines it into one value
Definition: the reduce() method applies a function to the accumulator and each element in the array (from left to right), and finally combines them into one value.
Syntax:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue) Copy code
Parameters:
Function: the function to be called for each element in the array.
// Parameters of callback function 1. total(must),Initial value, Or the value returned by the callback last time 2. currentValue(must),The value of the current element of the array 3. index(Optional), Index value of the current element 4. arr(Optional),Array object itself Copy code
Initialvalue (optional): Specifies the first parameter of the first callback.
When the callback is first executed:
- If initialValue is provided when calling reduce, the first total will be equal to initialValue, and currentValue will be equal to the first value in the array;
- If initialValue is not provided, total is equal to the first value in the array and currentValue is equal to the second value in the array. At this time, if the array is empty, TypeError will be thrown.
- If the array has only one element and no initialValue is provided, or if initialValue is provided but the array is empty, the callback will not be executed and the unique value of the array will be returned.
eg:
// Array summation let sum = [0, 1, 2, 3].reduce(function (a, b) { return a + b; }, 0); // 6 // Convert a two-dimensional array to a one-dimensional array and expand the array elements let flattened = [[0, 1], [2, 3], [4, 5]].reduce( (a, b) => a.concat(b), [] ); // [0, 1, 2, 3, 4, 5] Copy code
reduceRight accumulates from right to left
This method is completely consistent with reduce except that it is in the opposite direction. Please refer to the introduction of reduce method above.
ES6: find() & findindex() find array members based on criteria
find() definition: used to find the first qualified array member and return it. If there is no qualified member, return undefined.
findIndex() definition: returns the position of the first qualified array member. If all members do not meet the conditions, it returns - 1.
These two methods
Syntax:
let new_array = arr.find(function(currentValue, index, arr), thisArg) let new_array = arr.findIndex(function(currentValue, index, arr), thisArg) Copy code
Parameters: (the parameters and syntax of these methods are similar)
Function: the function to be called for each element in the array.
// Parameters of callback function 1. currentValue(must),The value of the current element of the array 2. index(Optional), Index value of the current element 3. arr(Optional),Array object itself Copy code
Thisvalue (optional): the value of this bound object when the callback function is executed. The default value is undefined
These two methods can identify NaN and make up for the deficiency of indexOf
eg:
// find let a = [1, 4, -5, 10].find((n) => n < 0); // Return element - 5 let b = [1, 4, -5, 10,NaN].find((n) => Object.is(NaN, n)); // Return element NaN // findIndex let a = [1, 4, -5, 10].findIndex((n) => n < 0); // Return index 2 let b = [1, 4, -5, 10,NaN].findIndex((n) => Object.is(NaN, n)); // Return index 4 Copy code
Browser compatibility (MDN):Chrome 45,Firefox 25,Opera 32, Safari 8, Edge yes,
ES6 keys() & values() & entries() traverse key name, key value, key name + key value
Definition: all three methods return a new Array Iterator object, which contains different values according to different methods.
Syntax:
array.keys() array.values() array.entries() Copy code
Parameter: none.
Chestnuts (from) ECMAScript 6 getting started):
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 code
In for Of, if you want to exit halfway through the traversal, you can use break to exit the loop.
If you don't use for Of loop, you can manually call the next method of the traverser object to traverse:
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']
Author: OBKoro1
Link: https://juejin.cn/post/6844903614918459406
Source: Nuggets
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, and for non-commercial reprint, please indicate the source.