1. Extend the operator
. Represents, convert an array to a comma-separated sequence of arguments as follows:
console.log(... [1,2,3]) // 1 2 3 console.log(1,... / / 1/2 and 4, 5) 2, 3, 4, 5 [.... The document querySelectorAll (' div ')] / [< div >, < div >, < div >] function add (x, y){ return x + y } const n = [3, 5] add(... n) // 8Copy the code
Extended operators can be used with normal functions as follows:
The function f (a, b, c, d, e) {the console. The log (a, b, c, d, e)} const age = [0, 1] f (1,... age,2,... [3]) // -1 0 1 2 3Copy the code
An extension operator can also be followed by an expression, as follows:
const x = 10
const arr = [
...(x > 0 ? ['a'] : []), 'b',
]
arr // ['a', 'b']
Copy the code
Important: If the extension operator is followed by an empty array, it will have no effect. In addition, the extension function is placed within parentheses only when the function is called, otherwise an error is reported.
The apply method replaces the function
Extension functions can expand arrays, so you won’t need the Apply method to convert arrays to function arguments.
Function f(x, y, z){console.log(x, y, z)} var a = [1,2,4] A) // math.max method //ES5 math.max. Apply (null, [14, 3, 99]) //ES6 math.max (... [12, 4, 55]) // equivalent to math.max (12, 4, 55) / / push method of the application of var = [0] var b = [three, four, five] / / ES5 Array. The prototype. Push. Apply (a, b) / / 0,1,2,3,4,5 / / ES6 Amy polumbo ush (... b)Copy the code
Extend the application of operators
-
Copy the array
Because arrays are composite data types, Const a1 = [1,2] const a2 = a1 a2[0] = 3 a1 // [3,2] // ES5 copy const a1 = [1,2] const a2 = A1. Concat () 23 a1 / a2 [0] = [1, 2] / / ES6 writing const b1 = [1, 3] const b2 = [...] b1 or b2 [...] = b1Copy the code
-
Merge array
Const a1 = [' b ', 'c'] const a2 = [' d '] const a3 = [' x ', 'y'] / / ES5 a1. Incorporating array concat (a2, a3) / / ES6 incorporating array [... a1, a2, // Both of the above are shallow copies, modifying the original array and synchronizing the new arrayCopy the code
-
Used with destruct assignment, the extension must be placed last or an error will be reported
// ES5 a = list[0], Rest = list. Slice (1) / / ES6 [rest] a,... = list / / other const [c] a,... = 2 1 c,2,4,5,4,6 [1] / / a,4,5,4,6 const [c] a,... = [] // a undefined c [] const [a,...c] = ['a'] // a 'a' c []Copy the code
-
String, converts a string to an array
[...'hello'] // [h,e,l,l,0] Copy the code
-
An object that implements the Iterator interface
Any object that defines the traverser interface, Can be used to let the real array extension operators nodelist = document. QuerySelectorAll (' div ') let array = nodelist [...] / / querySelectorAll What is returned is an array of classes that is converted to a real array by the extension operatorCopy the code
-
Map and Set destructions, Generator functions
The extension operator calls the Iterator interface, and as long as there is an Iterator object, Can be used to expand the operator / / Map Map = new Map ([[1, 'a'], [2, 'b'], [3, 'c'],]) let arr = [... Map. The keys ()] / / 1, 2, 3 let arr = [...map.values()] // 'a', 'b', 'c' //Generator const go = function*(){yield 1; yield 2; yield 3; } [...go()] // [1, 2, 3]Copy the code
2. Array.from()
The array. from method is used to convert two types of objects into real arrays. 1, Array-like objects and traversable objects (wrap sets and maps), as follows:
let arrLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
}
// ES5
var a1 = [].slice.call(arrLike)
// ES6
var a2 = Array.from(arrLike)
Copy the code
In practice, things like the Nodelist collection returned after retrieving the DOM, and the arguments objects inside the function are class arrays, converted to real arrays via array. from.
/ / the NodeList object let ps = document. QuerySelectorAll (' p ') Array. The from (ps). The filter (p = > {return p.t extContent. Length > 100}) Function foo(){var arg = array. from(arguments)} Array. The from every Array into an Array. The from (' hello ') / / [' h ', 'e', 'l', 'l', 'o'] let nl = new Set ([1, 2]) Array. The from (nl) / / [1, 2] / / if it is really an Array is returned as an Array, the from ([1, 2, 3]) / / [1, 2, 3]Copy the code
. Extension operators can also convert certain class arrays to arrays, such as arguments and NodeList collections
Objects with lenght attributes can be converted to arrays through array. from, but extension operators cannot.
Array.from({lenght:3}) // [undefined, undefined, undefined]
Copy the code
For older browsers, you can use the array.prototype. slice method instead
Array.from can also take a second argument, like map, that operates on each element and puts the processed value into the returned Array.
Const arrlike = new Set([1,2,3]) array. from(arrlike, x => x * x) // = array. from(arrlike).map(x => x * x) // [1, 4, 1) 9] // Note: If this is used in a map, we can pass in the third parameter of array. from to bind thisCopy the code
Array.from converts various values to real arrays and also provides map-related functionality, which means that if you have a raw data structure, you can first convert it to an Array and then use array-related methods.
3. Array.of()
Used to convert a set of values into an array. It is used to compensate for the difference caused by the different number of parameters in the Array function
Array of (3,11,6) / / [3, 11, 6] Array of (3) / / [3] Array) of (4). The length / / 1Copy the code
4. Array instance copyWithin()
Copies an element at a specified location in the current array to another location and overwrites the original element at that location, modifying the current array
Start (optional) : reads data from this location. Default: 0. End (optional) : reads data from this location. Let p = [1,2,3,4,5,6,7] p.copopywithin (0,5,7) [6, 7, 3,4,5,6,7]Copy the code
5. Find () and findIndex() of array instances
Find is used to find eligible members of an array. It takes a callback function to find a return value true, or undefined if none exists
Let s = [1,2,3,4,5,6] s.type (x => x > 4) // 5 find callback has three arguments value // current value index // current position arr // original arrayCopy the code
FindIndex is similar to find except that it returns -1 and returns the position of the qualified value instead of the value.
Let s = [1,2,3,4,5,6] s.type (x => x > 4) // 4Copy the code
Both find and findIndex accept the second argument
function o(p){ return p > this.age } const u = {name: 'cx', age: 11} const y = [8,11,22,2,4] y.pinindex (o, u) // 2Copy the code
6. Array instance fill()
Fills an array with the given value
Let sz = [1,2,3,4,5,6] sz.fill(1) // [1,1,1,1,1,1,1] sz.fill(1,0,3) // Sz.fill (1,3) // if the last parameter is omitted, it defaults from the start position to the end of the array's default lengthCopy the code
7. Array instance entries(), keys(), values()
The three methods are mainly used for traversing a number group, and can be used for… of… Traversal of keys() for key names, values for key values, and entries() for key-value pairs
let bo = ['a', 'c']
for(let r of bo.keys()){
console.log(r) // 0 1
}
// 0 1
for(let n of bo.values()){
console.log(n)
}
// a c
for(let s of bo.entries()){
console.log(s)
}
// [0, "a"]
// [1, "c"]
Copy the code
8. Array instance includes()
Used to indicate whether an array contains a given value, and returns a Boolean value
Let I = ['a',1,2,3] i.includes() // false i.includes(1) // true i.includes(10) // falseCopy the code
Differences between indexOf and includes
IndexOf // is not semantic enough. It is used to find the first occurrence of a parameter, so it is compared to -1, and NaN is misjudged because === is used internally. // [NaN].core. includes(NaN) //Copy the code
The difference between Map and Set has methods and includes
The Map has method is used to look up key names and the Set has method is used to look up valuesCopy the code
9. Array instance Flat (), flatMap()
Flat () transforms a nested two-dimensional array into a one-dimensional array, or flat(multidimensional number) or Infinity directly into a one-dimensional array if needed
Let rw = [1, 2, 3, 4 and 6], 7] rw. Flat () / / [1, 2, 3, 4, 5, 6, 7] let the dw = [1, 2, 3, 4 and 6, 7, 8], [2, (' a ', 'b'), 4, 5]], [5, 6,]] dw. The flat (3) / / [1, 2, 3, 4, 5, 6, 7, 8, 2, "a", "b", 4, 5, 5, 6] Infinity dw. Flat (Infinity) // [1, 2, 3, 4, 5, 6, 7, 8, 2, "a", "b", 4, 5, 5, 6]Copy the code
FlatMap () maps the array and then flat the array of returned values without changing the original array. FlatMap can expand only one layer array.
Let mp = 5-tetrafluorobenzoic [2] mp. FlatMap ((item) = > [item, item * 2]) / / [2, 4, 3, 6, 4, 8, 5, 10] = = = = mp. The map ((item) = > [item, Item) / / * 2] [[2, 4], [3], [4, 8], [5, 10]] mp. Flat () / / [2, 4, 3, 6, 4, 8, 5, 10]Copy the code
10. Empty arrays (to avoid empty arrays)
A void in an array means that there is no value at any point in the array. In addition, the empty space is not undefined. If the value of a position is undefined, then the position still has a value.
Array(3) // [, , ,]
Copy the code
Empty seats are ignored in most cases in ES5
- forEach(), filter(), reduce(), every() and some() skip empty Spaces - map() skip empty Spaces but keep the value - join() and toString() skip empty Spaces === undefined, Undefined and NULL are treated as empty stringsCopy the code
In ES6, empty space is converted to undefined
- Array.from([1,,2]) // [1, undefined, 2] - [...['a',,'b']] // [ "a", undefined, "B"] entries() keys() values() find() findIndex() // Will be treated as undefined.Copy the code
Welcome to pay attention to the public account [Xiaoyao students]
ES6 Introduction series
ES6 Introduction to let and cont
ES6 introduction to variable deconstruction assignment
ES6 starter string extension
ES6 – An extension to get started with re
ES6 introduction to numerical extension
Extension of ES6 introductory functions
Git tutorial
Front-end Git basics tutorial