preface
In the development, the use of array scenarios are very many, everyday also involves a lot of array API/related operations, has not been a piece of the content of the summary, many times even if used a few times this API, in the development is easy to forget, or to Google. So I hope to have a more systematic summary of this piece of content, in this context, there is this article, if you like it can point wave like/attention, support, I hope you can gain something after reading this article.
Front-end advanced accumulation, public account, GitHub
This article is a long one, so it is recommended to click “like” to save it and read it again.
Create an array:
Var a = [3, 11, 8]; var a = [3, 11, 8]; / /,11,8 [3]; // New Array === Array. It doesn't matter whether new is added or not. var a = Array(); // [] var a = Array(3); // [,,] var a = Array(3,11,8); / /,11,8 [3]Copy the code
ES6 array.of () returns an Array of all parameter values
Definition: Return an array of all parameter values, or an empty array if there are no parameters.
Purpose: The purpose of array.of () is to solve the problem that the constructor behaves differently due to the number of parameters.
let a = Array.of(3, 11, 8); // [3,11,8] let a = Array. Of (3); / / [3]Copy the code
ES6 arrary.from () turns the two types of objects into true arrays
Definition: used to convert two types of objects into a true array (return the new array without changing the original object).
Parameters:
First argument (required): Object to be converted into a true array.
Second argument (optional): An array-like map method that processes each element and puts the processed value into the returned array.
Third argument (optional): to bind this.
/ / 1. The object has length attribute let obj = {0: 'a', 1: 'b', 2: 'c', length: 3}; let arr = Array.from(obj); // ['a','b','c']; String, Set, NodeList let arr = Array. From ('hello'); // ['h','e','l','l','o'] let arr = Array.from(new Set(['a','b'])); // ['a','b']Copy the code
Methods:
The array prototype provides a lot of methods, but there are three types of methods, one that changes the value of the array, one that doesn’t change the array, and the way to iterate over the array.
Alter 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.fillCopy the code
For methods that can change the array, be careful to avoid the option of changing the array in the loop, such as changing the length of the array, resulting in a problem with the length of the loop.
Splice () adds/removes array elements
Definition: The splice() method adds/removes items to/from an array, and then returns the deleted items
Grammar: array splice (index, howmany, item1,… ,itemX)
Parameters:
- Index: Required. An integer that specifies the position to add/remove items. A negative number specifies the position from the end of the array.
- Howmany: Optional. Number of items to delete. If set to 0, the project will not be deleted.
- item1, … , itemX: Optional. The new item added to the array.
Return value: If an element was deleted, a new array containing the deleted items is returned.
Eg1: Delete elements
let a = [1, 2, 3, 4, 5, 6, 7]; let item = a.splice(0, 3); / / [1, 2, 3]. The console log (a); // [4,5,6,7] // delete 3 elements from array index 0. Let item = a.plice (-1, 3); // [7] // Delete three elements from the last element, and only 7 is deleted because of the last elementCopy the code
Eg2: delete and add
let a = [1, 2, 3, 4, 5, 6, 7]; Let item = a.plice (0,3,' add '); / / [1, 2, 3]. The console log (a); / / / / [' add ', 4, 7] from the array subscript 0, delete three elements, and add the elements' add 'let b = [1, 2, 3, 4, 5, 6, 7]. Let item = b.plice (-2,3,' add 1',' add 2'); / / [6, 7]. The console log (b); // [1,2,3,4,5,' add 1',' add 2']Copy the code
Eg3: Add only without deleting:
let a = [1, 2, 3, 4, 5, 6, 7]; Let item = a.plice (0,0,' add 1',' add 2'); Console. log(a); // [] return an empty array console.log(a); / / / 'add 1', 'added 2', 1,2,3,4,5,6,7] let b = [1, 2, 3, 4, 5, 6, 7]. Let item = b.plice (-1,0,' add 1',' add 2'); Console. log(b); // [] return the empty array console.log(b); // [1,2,3,4,5,6,' add 1',' add 2',7] adds two elements before the last elementCopy the code
From the above three chestnuts it can be concluded that:
- If there are not enough elements in the array, it will be deleted until the last element
- The element of the operation, including the first element
- You can add many elements
- The addition is added before the beginning element
Sort () Sort an array
Definition: the sort() method sorts the elements of an array and returns the array.
Parameter Optional: A comparison function that specifies the sort order.
By default, if the sort() method does not pass a comparison function, it defaults to alphabetic ascending order. If it is not an element or a string, the toString() method is called to convert the element to the Unicode point of the string and then compare the characters.
Var a = ["Banana", "Orange", "Apple", "Mango"]; a.sort(); // ["Apple","Banana","Mango","Orange"] Some of the numbers are going to be a little bit higher than the other numbers, which is obviously not what we want var a = [10, 1, 3, 20,25,8]; The console. The log (a.s ort ()) / /,10,20,25,3,8 [1];Copy the code
Compare the two arguments to the function:
The comparison function of sort takes two default arguments, which we receive in the function. These are the two elements of the array to be compared. Usually we use a and b to receive the two elements to be compared:
- If the comparison function returns a value <0, then a is placed before b;
- If the comparison function returns 0, then the relative positions of a and b are unchanged;
- If the comparison function returns a value greater than 0, then b is in front of a;
For a deeper look at the internal implementation and processing mechanisms of the sort() method, see this article for an in-depth look at javascript’s sort method
Sort sort
-
Array elements are in ascending or descending order of numbers:
Var array = [10, 1, 3, 4,20,4,25,8]; Array. Sort (function(a,b){return a-b; array. Sort (function(a,b){return a-b; }); console.log(array); / /,3,4,4,8,10,20,25 [1]; Array. sort(function(a,b){return b-a; return b-a; }); console.log(array); / /,20,10,8,4,4,3,1 [25];Copy the code
-
Array multi-condition sort
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){return b.age -a.age}else{// If (a.id == b.id) return b.age -a.age}else{// If (a.id == b.id) return b.age 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 the code
-
Custom comparison functions, the sky is your limit
Similarly: Using the return value, we can write any comparison function we want
var array = [{name:'Koro1'},{name:'Koro1'},{name:'OB'},{name:'Koro1'},{name:'OB'},{name:'OB'}]; Array. sort(function(a,b){if(a.name === 'Koro1'){return -1}else{// if(a,b){return -1}else{// if(a,b){return -1}else{// if(a,b){return -1} A row in the back of the b return 1}}) / / [{" name ":" Koro1 "}, {" name ":" Koro1 "}, {" name ":" Koro1 "}, {" name ":" OB "}, {" name ":" OB "}, {" name ":" OB "}]Copy the code
Pop () removes the last element from an array
Definition: The pop() method removes the last element from an array and returns that element.
Parameter: None.
Let a = [1, 2, 3]; let item = a.pop(); // 3 console.log(a); / / [1, 2]Copy the code
Shift () removes the first element of the array
Definition: The shift() method removes the first element of an array and returns that element.
Parameter: None.
Let a = [1, 2, 3]; let item = a.shift(); // 1 console.log(a); / / [2, 3]Copy the code
Push () adds an element to the end of the array
Definition: The push() method adds one or more elements to the end of an array and returns the new length.
Parameters: Item1, Item2,… , itemX, the element to add to the end of the array
Let a = [1, 2, 3]; Let item = a.ush (' end '); // 4 console.log(a); // [1,2,3,' end ']Copy the code
unshift()
Definition: The unshift() method adds one or more elements to the beginning of an array and returns the new length.
Parameters: Item1, Item2,… , itemX, the element to add to the beginning of the array
Let a = [1, 2, 3]; Let item = a.unitshift (' start '); // 4 console.log(a); // [' start ',1,2,3]Copy the code
Reverse () Reverses the order of the elements in an array
Definition: The reverse() method is used to reverse the order of the elements in an array.
Parameters: no
Let a = [1, 2, 3]; a.reverse(); console.log(a); / / [3, 2, 1]Copy the code
ES6: copyWithin() specifies a member at a location to copy to another location
Definition: within the current array, copies members from a specified location to another location, and returns the array.
Grammar:
array.copyWithin(target, start = 0, end = this.length)
Copy the code
Parameters:
All three parameters are numeric values. If not, they are automatically converted to numeric values.
- Target (required) : Replace data from this location. If it’s negative, it’s reciprocal.
- Start (Optional) : Data is read from this position. The default value is 0. If it’s negative, it’s reciprocal.
- End (optional) : Stop reading data at this position, which is equal to the array length by default. Use negative numbers to specify the position at the end of the array.
Browser compatibility (MDN): Chrome 45,Edge 12,Firefox32,Opera 32,Safari 9, IE does not support
eg:
// 2 is equal to position 3, 1 of 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'] / / 2 position began to be replaced, 3 start reading to replace 5 location stop in front of the replacement A.c opyWithin,3,5 (2) / / [" OB1, "" Koro1", "Koro2", "OB3," "OB3," "Koro3", "OB4", "Koro4", "OB5", "Koro5"]Copy the code
From the above chestnuts:
- The first argument is the position of the element to start replacing
- The range of positions to replace the data: the second argument is the element to start reading, and the third argument is the element to stop reading
- The length of the array doesn’t change
- After reading a few elements, replace a few elements from where you started
ES6: fill() fills the array
Definition: To fill an array with a given value.
Parameters:
First element (required): The value to populate the array
Second element (optional): The start position of the fill, which defaults to 0
Third element (optional) : the end of the padding, which defaults to this.length
MDN browser compatibility
['a', 'b', 'c'].fill(7)
// [7, 7, 7]
['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']
Copy the code
(8 methods) without changing the original array:
ES5: Slice, Join, toLocateString, toStrigin, cancat, indexOf, lastIndexOf, ES7: includesCopy the code
Slice () shallow-copies the elements of the array
Definition: The method returns a shallow copy of a portion of the array selected from start to finish (excluding the end) into a new array object, and the original array is not modified.
Note: Strings also have a slice() method that extracts the string, so don’t get confused.
Grammar:
array.slice(begin, end);
Copy the code
Parameters:
Begin (Optional): Indicates the index value. Negative values are accepted and elements in the original array are extracted from the index. The default value is 0.
End (optional): the value of the index (not included), accepts a negative value, and ends extraction of the original array elements before this index. The default value is the end of the array (including the last element).
let a= ['hello','world']; Let b = a.s lice (0, 1); // ['hello'] a[0]=' alter array '; console.log(a,b); // [' alter array ','world'] ['hello'] b[0]=' alter array '; console.log(a,b); // [' alter array ','world'] [' alter array ']Copy the code
As above: the new array is shallow copy, the elements are simple data types, and the changes do not interfere with each other.
If it is a complex data type (object, array), changing one changes the other.
let a= [{name:'OBKoro1'}]; let b=a.slice(); console.log(b,a); / / / {" name ":" OBKoro1}] [{" name ":" OBKoro1} "] / / a [0]. Name = 'to change the original array; // console.log(b,a); / / / {" name ":" to change the original array "}] [{" name ":" to change the original array "}] [0]. / / b name = 'change copy an array, b [0]. Belonged to =' change copy array; / / / {" name ":" change copy an array ", "belonged to" : "change copy an array"}] [{" name ":" change copy an array ", "belonged to" : "change copy an array"}]Copy the code
The reason for this is explained in the definition: slice() is a shallow copy. For complex data types, a shallow copy copies only a pointer to the original array, so either changing the original array or the shallow copy changes the data in the original array.
Join () array to string
Definition: The join() method is used to put all the elements of an array into a string, separated by the specified delimiter, and return the resulting string.
Grammar:
array.join(str)
Copy the code
Parameters:
STR (optional): Specifies the delimiter to be used. The default is a comma.
let a= ['hello','world'];
let str=a.join(); // 'hello,world'
let str2=a.join('+'); // 'hello+world'
Copy the code
What happens when the elements in an array are also arrays or objects using join or toString below?
let a= [['OBKoro1','23'],'test']; let str1=a.join(); / / OBKoro1, 23, test the let b = ({name: 'OBKoro1, age:' 23 '}, 'test']. let str2 = b.join(); // [object object],test // Object to string recommendation json. stringify(obj);Copy the code
So the join()/toString() method will call join()/toString() if the array element is an array, and if it is an object, the object will be converted to an [object object] string.
ToLocaleString () Turns an array into a string
Definition: Returns a string representing the elements of an array. The string consists of the return value of toLocaleString() for each element in the array joined (separated by commas) by calling the join() method.
Grammar:
array.toLocaleString()
Copy the code
Parameter: None.
let a=[{name:'OBKoro1'},23,'abcd',new Date()]; let str=a.toLocaleString(); // [Object Object],23,abcd,2018/5/28 PM 1:52:20Copy the code
If you call toLocaleString on an array, each element in the array calls its own toLocaleString method, an object calls toLocaleString on an object, and a Date calls toLocaleString on a Date.
ToString () array toString is not recommended
Definition: The toString() method converts an array into a comma-linked string.
Grammar:
array.toString()
Copy the code
Parameter: None.
This method has the same effect as the join method, which is used to convert an array to a string, but it has no advantages over the Join method and cannot customize the string delimiter, so it is not recommended.
Note that this method is called to automatically convert the array to a string when an array or string is operated on
Let b= ['toString',' demo '].tostring (); Let a= [' call toString',' join after me ']+' la la la '; // Call toString, concatenation after me la la laCopy the code
cancat
Definition: Method is used to combine two or more arrays, returning a new array.
Grammar:
var newArr =oldArray.concat(arrayX,arrayX,...... ,arrayX)Copy the code
Parameters:
ArrayX (mandatory) : This parameter can be either a concrete value or an array object. It could be any number of them.
eg1:
let a = [1, 2, 3]; let b = [4, 5, 6]; Let newVal= a.cat (b); Let c = [7, 8, 9] let newVal2 = a.concat(b, c); / /,2,3,4,5,6,7,8,9 [1] / / add elements let newVal3 = a.c oncat (' add elements', b, c, 'and a'); / / [1, 2, 3, 4 "add elements,",5,6,7,8,9, "plus a"] / / merge nested arrays will shallow copy nested let d = [1, 2]; let f = [3,[4]]; let newVal4 = d.concat(f); / / [1, 2, 3, [4]]Copy the code
ES6 extension operator… Merge arrays:
Because ES6’s syntax is more concise and easy to understand, I now mostly merge arrays… To deal with… Operator to implement each of the chestnuts of cancat, with more simplicity and a highly customizable array element position effect.
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 the code
For more on extenders, check out ECMAScript 6
IndexOf () looks for the presence of an element in the array and returns the index
Definition: Returns the first index in an array where a given element can be found, or -1 if it does not exist.
Grammar:
array.indexOf(searchElement,fromIndex)
Copy the code
Parameters:
SearchElement (required): The element to be searched
FromIndex (optional): The position to start the search (cannot be greater than or equal to the length of the array, return -1). Negative values are accepted. The default value is 0.
Strictly equal search:
The indexOf search for an array is different from the indexOf search for a string. The indexOf search for an array uses strict equality === to search for elements.
Note: indexOf() does not recognize NaN
eg:
Let a = [' la-la-la, 2,4,24, NaN]. The console log (Anderson ndexOf (', ')); // -1 console.log(a.indexOf('NaN')); // -1 console.log(a.inodexof (' la la ')); // -1 console.log(a.inodexof (' la la ')); / / 0Copy the code
Usage scenario:
- Array to heavy
- Perform operations based on the obtained array index, changing the values in the array, and so on.
- Check whether the system exists and perform 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, or -1 if none exists. (Looking forward from the back of the array)
Grammar:
arr.lastIndexOf(searchElement,fromIndex)
Copy the code
Parameters:
SearchElement (required): The element to be searched
FromIndex (optional): The start position of the reverse search. The default array length is -1, that is, the entire array is searched.
There are three rules about fromIndex:
-
Comes at a time. If the value is greater than or equal to the length of the array, the entire array is looked up.
-
A negative value. Think of it as an offset forward from the end of the array. (For example, -2, start with the second element of the array.)
-
A negative value. If the absolute value is greater than the array length, the method returns -1, that is, the array is not looked up.
Let a = [' OB ', 4, 'Koro1', 1, 2, 'Koro1, three, four, five,' Koro1]; // let b= a.astIndexof ('Koro1',4); Let b= a.astindexof ('Koro1',100); // let b= a.astindexof ('Koro1',100); // let b= a.astIndexof ('Koro1',-11); // let b= a.astIndexof ('Koro1',-11); Let b= a.astIndexof ('Koro1',-9); let b= a.astindexof ('Koro1',-9); // Look for the second element (4) and return -1Copy the code
ES7 includes() looks for an element in the array and returns a Boolean
Definition: Returns a Boolean value indicating whether an array contains a given value
Grammar:
array.includes(searchElement,fromIndex=0)
Copy the code
Parameters:
SearchElement (required): The element to be searched
FromIndex (Optional): The default value is 0. This parameter indicates the start position of the search. A negative value is acceptable. If the value exceeds the array length, the array will not be searched and false will be returned. If the absolute value of a negative value exceeds the length of the array, the search starts at 0.
The includes method is designed to compensate for the shortcomings of the indexOf method:
- The indexOf method is not recognized
NaN
- The indexOf method checks whether it contains a value that is not semantically sufficient and needs to determine whether it is not equal to
- 1
, the expression is not intuitive enough
eg:
let a=['OB','Koro1',1,NaN]; // let b=a.includes(NaN); // let b= a.ncludes ('Koro1',100); // let b= a.ncludes ('Koro1',100); // let b=a. ncludes('Koro1',-3); // let b= a.ncludes ('Koro1',-100); // let b= a.ncludes ('Koro1',-100); // If the value of a negative value exceeds the length of the array, search the entire arrayCopy the code
Compatibility (MDN): chrome47, Firefox 43,Edge 14,Opera 34, Safari 9,IE not implemented.
Traversal methods (12):
There are 12 methods in js to iterate through the array without changing the original array:
ES5: forEach, every, some, filter, map, reduce, reduceRight, ES6: find, findIndex, keys, values, entriesCopy the code
About traversal:
- For details on the efficiency of traversal, see this detailed JS traversal
- Try not to modify the values to be traversed later
- Try not to change the length of the array (delete/add) while iterating.
forEach
Definition: Perform a callback in ascending order for each item in the array that contains a valid value.
Grammar:
array.forEach(function(currentValue, index, arr), thisValue)
Copy the code
Parameters:
Function (must): The function that needs to be called for each element in the array.
CurrentValue (mandatory), the value of the current element of the array 2. index(optional), the index value of the current element 3. arr(optional), the array object itselfCopy the code
ThisValue (optional): The value of the object bound to this when the callback function is executed. The default is undefined
What you should know about forEach() :
- You can’t exit the loop, you can only use
return
Exit the callback and proceed to the next callback. - It always returns undefined, even if you return a value.
The following similar syntax also applies to these rules
The callback function is not executed for an empty array. 2. The callback function is skipped for elements that have been deleted during iteration, or for empty elements. The number of iterations is determined before the first iteration, that the elements added to the array are not traversed. 4. If an existing value has been changed, the value passed to the callback is the value traversed to their point of time.Copy the code
eg:
let a = [1, 2, ,3]; // Let obj = {name: 'OBKoro1'}; Let result = a.finach (function (value, index, array) {a[3] = 'change element '; A.ush (' added to the end, not traversed ') console.log(value, 'first argument passed by forEach '); // Print 1,2, change element console.log(this.name); // OBKoro1 prints three times this bound to the obj object // break; // Return value; Console. log(' will not be executed because return will execute the next loop callback ')}, obj); console.log(result); // Return undefined even if it returns a valueCopy the code
Every checks whether all elements of the array meet the criteria
Definition: A method that checks whether all elements of an array meet the conditions defined by the function
Grammar:
array.every(function(currentValue, index, arr), thisValue)
Copy the code
Parameters :(the parameters of these methods have similar syntax)
Function (must): The function that needs to be called for each element in the array.
CurrentValue (mandatory), the value of the current element of the array 2. index(optional), the index value of the current element 3. arr(optional), the array object itselfCopy the code
ThisValue (optional): The value of the object bound to this when the callback function is executed. The default is undefined
Method return value rule:
- If one element in the array is detected as unsatisfactory, the entire expression returns false and the remaining elements are not tested.
- Returns true if all elements meet the criteria. =
eg:
function isBigEnough(element, index, array) { return element >= 10; } let result = [12, 5, 8, 130, 44]. Every (isBigEnough);} let result = [12, 5, 8, 130, 44]. // false let result = [12, 54, 18, 130, 44].every(isBigEnough); // accept arrow function [12, 5, 8, 130, 44]. Every (x => x >= 10); // false [12, 54, 18, 130, 44].every(x => x >= 10); // trueCopy the code
Some Whether there are elements in the array that satisfy the criteria
Definition: Whether there are elements in an array that satisfy the criteria
Grammar:
array.some(function(currentValue, index, arr), thisValue)
Copy the code
Parameters :(the parameters of these methods have similar syntax)
Function (must): The function that needs to be called for each element in the array.
CurrentValue (mandatory), the value of the current element of the array 2. index(optional), the index value of the current element 3. arr(optional), the array object itselfCopy the code
ThisValue (optional): The value of the object bound to this when the callback function is executed. The default is undefined
Method return value rule:
-
If one of the elements satisfies the condition, the expression returns true, and the remaining elements are not tested.
-
If there are no elements that satisfy the condition, false is returned.
function isBigEnough(element, index, array) { return (element >= 10); } let result = [2, 5, 8, 1, 4]. Some (isBigEnough); // false let result = [12, 5, 8, 1, 4].some(isBigEnough); // trueCopy the code
Filter Filters the original array and returns the new array
Definition: Returns a new array containing all the elements of the tests implemented by the provided function.
Grammar:
let new_array = arr.filter(function(currentValue, index, arr), thisArg)
Copy the code
Parameters :(the parameters of these methods have similar syntax)
Function (must): The function that needs to be called for each element in the array.
CurrentValue (mandatory), the value of the current element of the array 2. index(optional), the index value of the current element 3. arr(optional), the array object itselfCopy the code
ThisValue (optional): The value of the object bound to this when the callback function is executed. The default is undefined
eg:
let a = [32, 33, 16, 40]; let result = a.filter(function (value, index, array) { return value >= 18; // Return all elements greater than 18 in array A}); console.log(result,a); / / [32,33,40] [32,33,16,40]Copy the code
Map processes each element in the array and returns a new array
Definition: Create a new array with the result of calling one of the provided functions for each element in the array.
Grammar:
let new_array = arr.map(function(currentValue, index, arr), thisArg)
Copy the code
Parameters :(the parameters of these methods have similar syntax)
Function (must): The function that needs to be called for each element in the array.
CurrentValue (mandatory), the value of the current element of the array 2. index(optional), the index value of the current element 3. arr(optional), the array object itselfCopy the code
ThisValue (optional): The value of the object bound to this when the callback function is executed. The default is undefined
eg:
let a = ['1','2','3','4']; Function (value, index, array) {return value + 'new element'}); console.log(result, a); / / / "1 new array elements", "2 new array elements", "3 new array elements", "four new array element"] [" 1 ", "2", "3", "4"]Copy the code
Reduce provides an accumulator for arrays that are merged into a single value
Definition: The reduce() method applies a function to the accumulator and to each element (from left to right) in the array, eventually merging it into a single value.
Grammar:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Copy the code
Parameters:
Function (must): The function that needs to be called for each element in the array.
CurrentValue (required), the value of the current element of the array 3. index(optional), the index of the current element 4. arr(optional), the array object itselfCopy the code
InitialValue (optional): Specifies the first parameter of the first callback.
When the callback is first executed:
- If initialValue is provided when reduce is called, then 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, then total equals the first value in the array and currentValue equals the second value in the array. If the array is empty at this point, TypeError will be raised.
- If an array has only one element and an initialValue is not provided, or if an initialValue is provided but the array is empty, the callback is not executed and the unique value of the array is returned.
eg:
Let sum = [0, 1, 2, 3].reduce(function (a, b) {return a + b; }, 0); / / 6 / / convert two-dimensional arrays into one dimensional array elements on the let flattened = [[0, 1], [2, 3], [4, 5]], the reduce ((a, b) = > a.c oncat (b), []); // [0, 1, 2, 3, 4, 5]Copy the code
ReduceRight accumulates from right to left
This method is completely consistent with reduce except in the opposite direction. For details, see the description of reduce method above.
ES6: find()& findIndex() finds array members based on conditions
Find () definition: to find the first member of an array that matches a condition and return that member, or undefined if there is none.
FindIndex () definition: return the position of the first member of an array that meets the criteria, or -1 if none of the members meet the criteria.
These two methods
Grammar:
let new_array = arr.find(function(currentValue, index, arr), thisArg)
let new_array = arr.findIndex(function(currentValue, index, arr), thisArg)
Copy the code
Parameters :(the parameters of these methods have similar syntax)
Function (must): The function that needs to be called for each element in the array.
CurrentValue (mandatory), the value of the current element of the array 2. index(optional), the index value of the current element 3. arr(optional), the array object itselfCopy the code
ThisValue (optional): The value of the object bound to this when the callback function is executed. The default is undefined
Both of these methods recognize NaN, which makes up for indexOf.
eg:
// find let a = [1, 4, -5, 10].find((n) => n < 0); / / return elements - 5 b = [1, 4, 5, 10, NaN]. Find ((n) = > Object. The is (NaN, n)); // findIndex let a = [1, 4, -5, 10]. FindIndex ((n) => n < 0); / / return index 2 let b = [1, 4, 5, 10, NaN]. FindIndex ((n) = > Object. The is (NaN, n)); // Return index 4Copy the code
Browser Compatibility (MDN):Chrome 45,Firefox 25,Opera 32, Safari 8, Edge Yes
ES6 keys()&values()&entries() Traversal key name, traversal key value, traversal key name + key value
Definition: Each of the three methods returns a new Array Iterator with different values depending on the method.
Grammar:
array.keys()
array.values()
array.entries()
Copy the code
Parameter: None.
Traversal chestnuts (from ECMAScript 6 Introduction) :
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
In the for… If you want to exit in the middle of the loop, you can use break to exit the loop.
If you don’t use for… The of loop can be traversed manually by calling the next method on the traverser 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
Entries () Browser Compatibility (MDN):Chrome 38, Firefox 28,Opera 25,Safari 7.1
Keys () :Chrome 38, Firefox 28,Opera 25,Safari 8,
Note: It is currently only supported in Safari 9, not in other browsers, and the Babel transcoder is not yet implemented
conclusion
Shout ~ finally write good, off and on, work also secretly stroke water of write a few days, although very hard, but now on the array operation method, the whole clear a lot, each API also understand a bit better, harvest a lot, if there is not correct article welcome each big guy spur! I hope you can learn something after reading this, if you like it, please click the wave to subscribe.
I hope that after watching the friends can click like/follow, your support is the biggest encouragement to me.
Front-end advanced accumulation, public account, GitHub, wx:OBkoro1, email: [email protected]
The above 2018.5.30
References:
ECMAScript6 Getting Started with array extensions
JavaScript Array
Learn more about javascript’s sort method
JavaScript array all API full decryption
Detail JS traversal
Determines whether a variable is an array
In JavaScript, how to find the intersection and difference set of two arrays?