❝
Learning needs to accumulate over a long period of time, achievements also need to accumulate, unremitting efforts to struggle. Accumulation is a kind of perseverance, is the only way from small to great, is the premise of success, is the process from quantitative change to qualitative change.
❞
Recently in the ruan yifeng ES6 array expansion, incidentally reviewed the ES5 array method and then summarized, I hope to help you 👍👍
Extension of the ES6 array
Extended operators (…)
Converts an array to a comma-separated sequence
console.log(1, ...[2, 3, 4], 5)
// 1, 2, 3, 4, 5Copy the code
Note: 1. If the extension operator is followed by an empty array, nothing happens
2. The extension operator is placed in parentheses only when the function is called, otherwise in []
“Assign an array“
const a1 = [1, 2];
/ / write oneconst a2 = [...a1];
/ / write twoconst [...a2] = a1;
Copy the code
“Merge array“
const arr1 = ['a'.'b'];
const arr2 = ['c'];
const arr3 = ['d'.'e'];
const newArr = [...arr1, ...arr2,...arr3];
console.log(newArr) //['a'.'b'.'c'.'d'.'e']
Copy the code
“Combined with deconstruction assignment“
If an extension operator is used for array assignment, it must be placed in the last bit of the argument, otherwise an error will be reported.
const [a, ...b] = ['a'.'b'.'c'.'d'.'e'];
console.log(a) //a
console.log(b) //["b"."c"."d"."e"]
Copy the code
“Extension operators can also turn strings into true arrays.“
One important benefit is the ability to correctly recognize four-byte Unicode characters.
console.log([...'haha'/ / [])"h"."a"."h"."a"]
Copy the code
Array.from()
Used to convert array-like objects and traversable objects into arrays,
let arrayLike = {
'0': 'a'. '1': 'b'. '2': 'c'. length: 3
}; letarr2 = Array.from(arrayLike); / / /'a'.'b'.'c'] Copy the code
The so-called array-like object has only one essential feature, that is, it must have the length attribute. Therefore, any object with length can be converted to an Array by the array. from method, whereas the extension operator cannot. 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.
Array.from(arrayLike, x => x * x);
/ / is equivalent toArray.from(arrayLike).map(x => x * x);
Array.from([1, 2, 3], (x) => x * x)
/ / [1, 4, 9]Copy the code
Array.of()
The array. of method converts a set of values to an Array. Array.of always returns an Array of parameter values. If there are no arguments, an empty array is returned
Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]
Array.of() // []
Array.of(undefined) // [undefined]
Array.of(1) // [1] Array.of(1, 2) // [1, 2] Copy the code
Find () and findIndex() of array instances
Find () is used to find the first eligible array member and return that member, or undefined if none exists.
[1, 4, -5, 10].find((n) => n < 0)
/ / - 5Copy the code
FindIndex () finds the first eligible array member and returns the index of that member, or -1 if no eligible member exists;
[1, 5, 10, 15].findIndex(function(value, index, arr) {
return value > 9;
/ / 2})Copy the code
fill()
Method fills an array with the given value.
['a'.'b'.'c'].fill(7)
/ / (7, 7, 7)
new Array(3).fill(7)
/ / (7, 7, 7)Copy the code
Fill (7, 1, 2) If the type of fill is an object, then the object assigned is the same memory address, not the deep-copy object.
Array instance entries(), keys() and values()
The only differences are that keys() is traversal of key names, values() is traversal of key values, and entries() is traversal of key value pairs.
const objArr = [
{
name: 'Joe'. age: 23
},
{ name: 'bill'. age: 25 }, { name: 'Cathy'. age: 26 } ] for(item of objArr.keys()){ console.log(item) } for(item of objArr.values()){ console.log(item) } for([index, item] of objArr.entries()){ console.log(index, item) } Copy the code
includes()
“Array.prototype.includes (target, start)“
Target: mandatory parameter, given value
Start: Optional argument, the starting position of the search. The default value is 0, if 0 is the reciprocal position, and if it exceeds the length of the array, starting from 0. The search method returns a Boolean value indicating whether an array contains a given value
[1, 2, 3].includes(2) // true
[1, 2, 3].includes(4) // false
[1, 2, NaN].includes(NaN) // true
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true [NaN].indexOf(NaN) Copy the code
Array instance flat(), flatMap()
The members of arrays are sometimes still arrays, array.prototype.flat () is used to “flatten” nested arrays into one-dimensional arrays. This method returns a new array with no effect on the original data. Flat () “flattens” only one layer by default. If you want to “flatten” a nested array of multiple layers, you can write the argument to the flat() method as an integer representing the number of layers you want to flatten, which defaults to 1.
[1, 2, [3, [4, 5]]].flat()
// [1, 2, 3, [4, 5]]
[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]
Copy the code
If you want to convert to a one-dimensional array regardless of the number of nesting levels, you can use the Infinity keyword as an argument.
[1, [2, [3]]].flat(Infinity)
/ / [1, 2, 3]Copy the code
If the array is empty, the flat() method skips the empty
[1, 2, , 4, 5].flat()
// [1, 2, 4, 5]
Copy the code
The flatMap() method performs a function on each member of the original Array (equivalent to array.prototype.map ()), and then flat() on the Array of returned values. This method returns a new array, leaving the original array unchanged.
// Equivalent to [[2, 4], [3, 6], [4, 8]].flat()[2, 3, 4].flatMap((x) => [x, x * 2])
// [2, 4, 3, 6, 4, 8]
Copy the code
FlatMap () can expand only one layer array.
// Equivalent to [[[2]], [[4]], [[6]], [[8]]. Flat ()[1, 2, 3, 4].flatMap(x => [[x * 2]])
[[2], [4], [6], [8]]Copy the code
ES6 array method
forEach()
“Iterating through an array, with no return value, is not allowed to write a return inside the loop, and does not change the array“
letArr =,22,33,44,66 [11] arr.forEach((item,index, arr) =>{
console.log(item, index, arr)
})
Copy the code
map()
“Iterating through the array returns a new array, without changing the original array“
letArr =,22,33,44,66 [11]let newArr = arr.map((item,index,arr) => {
return item*10
})
console.log(newArr) //[110, 220, 330, 440, 660]
letnewArr2 = arr.map(String); // Change the element of the array to Stringconsole.log(newArr2) //["11"."22"."33"."44"."66"] letNewArr3 = newarr2. map(Number) // Changes the elements of the array to Numberconsole.log(newArr3) //[11, 22, 33, 44, 66] Copy the code
filter()
“Filter out the elements that do not meet the criteria, and place the elements that do meet the criteria into a new array, leaving the original array unchanged“
let arr4 = arr.filter(item => item%2 === 0);
console.log(arr4) //[22, 44, 66]
Copy the code
reduce()
“Method receives a function as an accumulator, and each value in the array (from left to right) is reduced to a value.“
- Find the sum of the array entries
letArray = [1, 2, 3, 4, 5];let temp = array.reduce((prev,cur) => {
console.log('prev',cur)
console.log('cur', cur)
return prev+cur;
}) console.log(temp) Copy the code
We pass in an initial value of 0, so we start with 0 prev, 3 cur, and 3 as the prev for the next callback, and so on, until we sum all the entries and return.
- The largest item of an array element
letArray = [1, 2, 3, 4, 5];var max = array.reduce((prev,cur)=>{
return Math.max(prev,cur)
})
console.log(max) //5
Copy the code
Since no initial value is passed in, we start with prev as the first item of the array, 3, and cur as the second item of the array, 9. Take the maximum of the two values and proceed to the next callback.
- Array to heavy
Var arr =,22,33,22,11 [11]var newArr = arr.reduce(function (prev, cur) {
prev.indexOf(cur) === -1 && prev.push(cur);
return prev;
},[]);
The console. The log (newArr) / /,22,33 [11]Copy the code
-
- Initialize an empty array
-
- (2) Look for the first item in the array to be reprocessed in the initialization array. If it can’t find it (it certainly can’t find it in the empty array), add it to the initialization array
-
- ③ Look for the second item in the array to be reprocessed in the initialization array. If no item is found, add it to the initialization array
-
- (4)…
-
- ⑤ Look for the NTH item in the array to be reprocessed in the initialization array. If not, add the item to the initialization array
-
- ⑥ Return the initialization array
every()
“Return true if each item is true, or false if one item is false“
letArr =,22,33,44,66 [11]let arr2 = arr.every((item,index,arr) => {
return item % 2 === 0
})
console.log(arr2) //false
Copy the code
some()
“Iterating over the array of elements, stopping the loop as long as one of them returns true, and returning a BooleanI'm not changing the original array
“
letArr =,22,33,44,66 [11]let arr3 = arr.some((item,index,arr) => {
console.log(index) //0
return item > 1
})
console.log(arr3) // true Copy the code
find()
“I find the first element that matches the criteria, I stop iterating,I'm not changing the original array
“
letArr =,22,33,44,66 [11]let arr4 = arr.find((value,index, arr) => {
return value % 3 === 0
})
console.log(arr4) //33
Copy the code
ES5 array method
splice()
“Method adds/removes items to/from an array and returns the deleted items. –Change the original array“
arrayObject.splice(index,howmany,item1,….. ,itemX)
- The index required. Integer to specify where items are added/removed, and negative numbers to specify positions from the end of the array.
- Howmany required. Number of items to delete. If set to 0, the project will not be deleted.
- item1, … ItemX is optional. The new item added to the array.
letArr = [1, 2, 3, 4, 5]letArr2 = arr.splice(2,2) // Subscript removes 2 elements from 2The console. The log (arr) / /,2,5 [1]The console. The log (arr2) / / [3, 4]Copy the code
concat()
“The join () method is used to join two or more arrays.“
arrayObject.concat(arrayX,arrayX,…… ,arrayX)
ArrayX is a required parameter, which can be a concrete value or an array object. It can be as many as you want.
letArr1 = [1, 2, 3, 4, 5];let arr2 = ['aa'.'bb'.'cc']
let arr3 = arr1.concat(arr2)
console.log(arr3) //[1, 2, 3, 4, 5, "aa"."bb"."cc"]
console.log(arr1.concat('qq'.'ww') //[1, 2, 3, 4, 5,"qq"."ww"]
Copy the code
The join () and toString ()
- arrayObject.join(separator)*
“The array_string () method is used to convert an array to a string. If no arguments are passed, the characters are separated by commas by default. If arguments are passed, the characters are separated by the specified delimiter“
- arrayObject.toString()
“This method takes no arguments and converts arrays to strings separated by commas.“
letArr1 = [1, 2, 3, 4, 5];var str1 = arr1.join()
var str2 = arr1.join(The '*')
The console. The log (str1) / / 1, 2, 3, 4, 5console.log(str2) //1*2*3*4*5
let arr3 = ['aa'.'bb'.'cc'] var arr4= arr3.toString() //aa,bb,cc Copy the code
Pop () and Shift () — change the array
“The pop() method removes and returns the last element of the array.“
“The shift() method removes the first element from an array and returns the value of the first element.“
The pop() method removes the last element of the arrayObject, reduces the array length by one, and returns the value of the element it removed. If the array is already empty, pop() does not change the array and returns undefined.
let arr2 = ['aa'.'bb'.'cc']
var arr3= arr2.pop()
console.log(arr3) // cc
console.log(arr2) //(2) ["aa"."bb"]
Copy the code
slice()
“Method returns the selected element from an existing array.“
arrayObject.slice(start,end)
conclusion
methods | describe |
---|---|
concat() | Joins two or more arrays and returns the result |
join() | Puts all the elements of an array into a string, separated by the specified delimiter |
pop() | Removes and returns the last element of the array |
push() | Adds one or more elements to the end of the array and returns the new length. |
revere() | Reverses the order of the elements in an array. |
shift() | Removes and returns the first element of the array |
slice | Returns the selected element from an existing array |
sort | Sort the elements of an array |
splice() | Removes the element and adds a new element to the array. |
toSource() | Returns the source code for this object. |
toString() | Converts an array to a string and returns the result. |
toLocaleString() | Converts an array to a local array and returns the result |
unshift() | Adds one or more elements to the beginning of the array and returns the new length. |
valueOf() | Returns the original value of an array object |
How do I generate an array like [1-100]
The fill () method
Array(100) generates an Array with 100 empty Spaces. This Array cannot be traversed using map(),forEach(),filter(), etc., because empty Spaces are skipped. (For of does not skip empty Spaces) then fill the Array with numbers using fill().
Array(3) // [empty × 100]
const arr1 = Array(100).fill(0).map((item, index) =>{ return index})
Copy the code
Array.from
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
const arr4 = Array.from(Array(100), (value, key) => key + 1);
Copy the code
Extended operators (…)
Keys () is a traversal of key names
const arr2 = [...Array(100).keys() ]
Copy the code
for of
This is not recommended
let arr = []
for(let x of Array(100).keys()){
console.log(x)
arr.push(x+1)
}
console.log(arr) Copy the code
How do I get the union, intersection, and difference of 2 arrays
And set
letArr1 = new Set (,2,3,4,3,2,1 [1]); / / {1, 2, 3, 4}
letArr2 = new Set (,3,2,66 [3]); / /,2,66 {3}Copy the code
let union = new Set([...arr1, ...arr2]); //Set{1, 2, 3, 4, 66}
console.log([...union]) //[1, 2, 3, 4, 66]
Copy the code
intersection
let intersect = new Set([...arr1].filter(x => arr2.has(x)));
The console. The log (intersects) / / {2, 3}Copy the code
Difference set
The difference set of arr1 with respect to ARR2
letdifference = new Set([...arr1].filter(x => ! arr2.has(x)));The console. The log (difference) / / {1, 4}Copy the code