1. Extend the operator

In ES6, a new… The operator, called the extension operator, in my extension summary of the function in ES6+ says that the argument to the function in ES6 has a REST argument, which is also… Operator, which allows the arguments passed during a function call to be stored in an array. The following

function add(. values){
   let sum = 0;
   values.forEach(value= >{ sum + = value; ] )return sum
}
letSum = add (1.2.3.4.5.6.7)Copy the code

The extended operator in an array, like the inverse of the REST argument, turns an array into a comma-separated sequence of arguments.

console.log(... [1.2.3.4.5.6.7]);
/ / 1,2,3,4,5,6,7

[...document.querySelectorAll('div')]
//<div> <div> <div>
Copy the code

Two operators (rest arguments and… Operators) can work together very conveniently

function  push(array, ... items){ array.push(... items) }Copy the code

Thanks to the extension operator, there is no need to use Apply to convert arrays to function parameters

//ES5
function f(x,y,z){
    / /...
}
f.apply(null[1.2.3])

//ES6
function f(x,y,z){ } f(... [1.2.3])
Copy the code

Application:

1. Merge arrays

// The array.concat ()API is used to merge arrays in ES5, and extension operators are available in ES6
let array = [1.2.3.4.5. [6.7.8.9]]
let array= [...[1.2.3.4],... [5.6.7],... [8.9.0]]
Copy the code

2. Used in conjunction with deconstruction assignment

let a ,array
[a,...array] = [1.2.3.4.5.6.7.8]

a/ / 1
array/ /,3,4,5,6,7,8 [2]
Copy the code

The above code passes the first element of the array to the right of the equals sign to A by destructuring assignment, and the following element to array. Note that if you use the extension operator for array assignment, you must place it only in the last bit of the argument, otherwise an error will be reported.

const [...butlast,last] = [1.2.3.4.5.6]

// Error !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Copy the code

3. Parameters of the function

As we’ve seen above, here…

4. The string

The extension operator converts a string into a true array

5. Convert objects of DOM nodes into arrays

See the code below:

let nodeList = document.querySelectorAll("div");
let array = [...nodeList]
Copy the code

NodeList is an object (an array-like object, but still an object), not an array, but can be converted to a true array using the extension operator, because the extension operator internally calls the Iterator interface for data structures. So any object that has an Iterato interface can use an extension, and the nodeList in the above code has an Iterator interface, so it can be used.

2.Array.from()

The array. form method is used to convert two types of objects into true arrays: array-like objects and traversable objects (new maps and sets in ES6).

The following code is an array-like object, and array. from converts it into a real Array.

let arrayLike = {
   "0":"a"."1":"b"."2":"c"
    length:3
}
let array = Arrat.from(arrayLike);//["a","b","c"]
Copy the code

In practice, common array-like objects are the NodeList collection returned by DOM operations and the arguments object inside functions, both of which can be converted to arrays by array. from.

Also, only data structures with the Iterator interface deployed can be converted to array. from, and if the converted object is an Array, an identical Array will be returned.

Array.from('hello');//['h','e','l','l','o']


let namesSet = new Set(['a'.'b']);
Array.from(namesSet)//['a','b']
Copy the code

We said that only structures that have an Iterator interface can use the extension operator. Array-like objects are actually objects that have length. In some cases, array. from does not translate correctly.

Array.from({length: 3})
//[undefined,undefined,undefined]
Copy the code

For browsers that do not deploy this method, the array.prototype. slice method can be used instead.

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 to
Array.from(arrayLike).map(x= > x*x);

Array.from([1.2.3],(x) => x*x)
/ /,4,9 [1]
Copy the code

If the second argument (like a map argument) uses this, the argument can also pass a third value that binds this.

3.Array.of()

The array.of () method is used to convert a set of values to an Array.

let array = Array.of(1.2.3.4.5);
array / / [1, 2, 3, 4, 5]
Copy the code

Does the code look familiar? Let array = array (1,2,3,4,5); let array (1,2,3,4,5);

Array(a)/ / []
Array(3)/ / /,,
Array(1.2.3)/ / [1, 2, 3]
Copy the code

In the above code, the number of parameters is 0, 1, and more will return different results, while array. of does not cause overloading because of the number of parameters, its behavior is very uniform.

Array.of()/ / []
Array.of(2)/ / [2]
Array.of(1.2)/ / [1, 2]
Array.of(undefined)//[undefined]
Copy the code

4. Array instance copyWithin()

The copyWithin method of an array instance copies the members of the current internal location to other locations (overwriting the original members) and then returns the current array, meaning that using this method changes the current array.

Array.prototype.copyWithin(target,start = 0,end = this.length)

(Optional) start: reads data from this position. The default value is 0. If the value is negative, it indicates the countdown

These three positions should all be subscripts, indicating the corresponding subscript, if not automatically converted to a value.

5. Find () and findIndex() of array instances

The find() and findIndex() methods on an array instance are used to find the first qualified member of the array. This takes a callback that all array members execute once until they find the first member that returns true. The difference is that find() returns a value. Findindex () returns the index. They can all take three arguments, in order: the current value, the current position, and the original array.

[1.2.3.4.5.6].find((n) = >n > 5) / / 6 (value)
[1.2.3.4.5.6].findIndex((n) = >n > 5) //5 (subscript)
Copy the code


It is important to note that the arguments in these two methods are callback functions, and we can use object.is () in callback functions to distinguish NaN from indexOf

6. Array instance fill()

The fill method fills an array with the given values

['a'.'b'.'c'].fill(7)
/ /,7,7 [7]
new Array(3).fill(7);
/ /,7,7 [7]
Copy the code

As you can see from the code above, the fill method is handy for initializing an empty array, overwriting existing elements, or passing the second and third arguments to indicate where to start and end the fill

['a'.'b'.'c'].fill(7.1.2)
Copy the code

7. Array instance entries(),keys(),values()

ES6 provides these three new methods for iterating over groups of numbers, all of which return an iterator object, which you can use for… of … Keys () is traversal of key names, values is traversal of key-value pairs, and entries are traversal of key-value pairs.

 for(let index of ['a'.'b'].keys()){console.log(index)}/ / 0 to 1

 for(let value of ['a'.'b'].keys()){console.logvalue)}//a b

 for(let [index,value] of ['a'.'b'].keys()){console.log(index,value)}//0 'a' 1 'b'
Copy the code

Note that the third line of [index,value] contains an array

8. Array instance includes()

The array.prototype. includes method returns a Boolean value indicating whether the Array contains a given value, similar to a string includes.

[1.2.3].includes(2) //true 
Copy the code

The method can also pass a second argument indicating where to start the search, reset to 0 if it is greater than the length of the array, or reciprocal if it is negative.

[1.2.3].includes(2.2) //false
Copy the code

This method is similar to indexOf, except that indexOf is not semantic enough to specify where to start a search, and the use of === in indexOf can cause NaN to misjudge. If includes uses a different algorithm, this problem is avoided.

9. Empty space of array

The empty space of an array is the empty space when only the size of the array is defined and no value is assigned when declaring an array

new Array(3);
/ / /,,
Copy the code

A vacancy is not undefined. A position equal to undefined is still valued. A vacancy is not worth anything, as can be proved by using the in operator


(forEach(),filter(),every(),some() skip the empty space, map() skip the empty space but keep the value, join(),toString() treat the empty space as undefined, Undefined and NULL are treated as empty strings. ES6 explicitly converts empty space to undefined. (Array.from, the extension operator treats it as undefined,copyWithin copies the empty space together, and fill treats the empty space as a normal Array position…)

In summary: Since the processing of empty seats is very inconsistent, it is important to avoid empty seats!!!!!

Well, the above is all of the ES6 array extension, I am a reference to ruan Yifeng “ES6 standard introduction —- third edition”,

Don’t forget to give this article a thumbs up if you find it useful. Ballpoint pen.