Extended operator (...)

ES6 introduced the rest parameters (in the form of "variable name ..."). Parameters with which the rest of the variable is an array can use an array of all operations.

function rest(...values){
    let sum=0;
    for(var val of values){
        sum+=val;
    }
    return sum;
}
add(1,2,3)//6

1. Meaning

Extended operator (Spread) is three dots (...). It is like the inverse of the rest parameter, the parameter sequence into an array separated by commas.

console.log(...[1, 2, 3])
// 1 2 3
console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5
[...document.querySelectorAll('div')]
// [<div>, <div>, <div>]

The operator is mainly used in a function call.

function push(array, ...items) {
array.push(...items);
}
function add(x, y) {
return x + y;
}
var numbers = [4, 38];
add(...numbers) // 42

Calling the above code, array.push (... items) and add (... numbers) two lines, it is a function of their use extended operator. The operator will be an array, the parameter sequence becomes.

Normal extended operator function parameters may be combined to use, it is very flexible.

function f(v, w, x, y, z) { }
var args = [0, 1];
f(-1, ...args, 2, ...[3]);

2. The method of alternative arrays apply

Since the operator can be extended to expand the array, there is no need apply method, the parameters of the function into the array.

// ES5 的写法
function f(x, y, z) {
// ...
}
var args = [0, 1, 2];
f.apply(null, args);
// ES6 的写法
function f(x, y, z) {
// ...
}
var args = [0, 1, 2];
f(...args);

The following is extended operator substituted apply a practical example of the method, the application method Math.max simplified wording obtaining a maximum array elements.

// ES5 的写法
Math.max.apply(null, [14, 3, 77])
// ES6 的写法
Math.max(...[14, 3, 77])
//  等同于
Math.max(14, 3, 77);

Code represents the above, since the JavaScript function does not provide the maximum seek array elements, can only be applied Math.max function, a parameter sequence into an array, then selecting the maximum value. After the operator has been extended, the Math.max can be directly used.

Another example is through the push function, added to the end of an array of another array.

// ES5 的写法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
Array.prototype.push.apply(arr1, arr2);
// ES6 的写法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);

ES5 written in the above code, the method can not push the parameter is an array, so I had to work by the apply method using the push method. With extended operator, the array can be passed directly to the push method.
Here is another example.

// ES5
new (Date.bind.apply(Date, [null, 2015, 1, 1]))
// ES6
new Date(...[2015, 1, 1]);

3. The extended application operator

3.1 merge array

Extended operator provides arrays into a new wording.

// ES5
[1, 2].concat(more)
// ES6
[1, 2, ...more]
var arr1 = ['a', 'b'];
var arr2 = ['c'];
var arr3 = ['d', 'e'];
// ES5 的合并数组
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]
// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]

3.2 in conjunction with destructuring assignment

Extended operator can be combined with the destructuring assignment, for generating arrays.

// ES5
a = list[0], rest = list.slice(1)
// ES6
[a, ...rest] = list
下面是另外一些例子。
const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest // [2, 3, 4, 5]
const [first, ...rest] = [];
first // undefined
rest // []:
const [first, ...rest] = ["foo"];
first // "foo"
rest // []

If you extend the array assignment operator is used only in the last parameter, otherwise it will error.

const [...butLast, last] = [1, 2, 3, 4, 5];
//  报错
const [first, ...middle, last] = [1, 2, 3, 4, 5];
//  报错

3.3 the return value of the function

JavaScript function returns a value only if the need to return multiple values, or only return an array of objects. Extended operator provides a workaround solution to this problem.

var dateFields = readDateFields(database);
var d = new Date(...dateFields);

The above code is extracted from the database data row, by extending the operator, directly to the constructor. Date.

3.4 String

Operators may also be extended into a real string array.

[...'hello']
// [ "h", "e", "l", "l", "o" ]

The above wording, there is a significant benefit, it is able to correctly identify 32-bit Unicode characters.

'x\uD83D\uDE80y'.length // 4
[...'x\uD83D\uDE80y'].length // 3

The first written above code, JavaScript 32-bit Unicode character will be identified as two characters, the operator uses extended do not have this problem. Thus, the function returns the length of the string is correct, the following can be written as.

function length(str) {
return [...str].length;
}
length('x\uD83D\uDE80y') // 3

All related to the operation of 32-bit Unicode characters function, we have this problem. Therefore, the best operators are rewritten with the extension.

let str = 'x\uD83D\uDE80y';
str.split('').reverse().join('')
// 'y\uDE80\uD83Dx'
[...str].reverse().join('')
// 'y\uD83D\uDE80x'

Code above, if the operator is not extended, the string is not correct Reverse operation.

3.5 object that implements the Iterator interface

Iterator interface of any object, can be converted to the real array with extended operator.

var nodeList = document.querySelectorAll('div');
var array = [...nodeList];

The above code, querySelectorAll method returns a nodeList object. It is not an array, but an array-like object. In this case, the operator can be expanded into an array of the real reason is that NodeList object implements the Iterator interface.

For an array of objects similar to those not deployed Iterator interface, operators can not expand its conversion into a real array.

let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
// TypeError: Cannot spread non-iterable object.
let arr = [...arrayLike];

The above code, arrayLike is an array-like objects, but not deployed Iterator interface, extended operator error is reported. In this case, the method can be used instead Array.from arrayLike into a real array.

Set 3.6Map and structure, Generator function

Extended operator calls are internal Iterator interface data structure, so long as the object having the Iterator interface, extended operator can use, such as Map structure.

let map = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
let arr = [...map.keys()]; // [1, 2, 3]

After running Generator function returns a visitor object, and therefore can use the extended operator.

var go = function*(){
yield 1;
yield 2;
yield 3;
};
[...go()] // [1, 2, 3]

The above code, the variable is a go Generator function, after execution returns an iterator object value visitor object performs spreading operator, will traverse the interior obtained, into an array.
If no iterator object interface, using extended operator, will be given.

var obj = {a: 1, b: 2};
let arr = [...obj]; // TypeError: Cannot spread non-iterable object

Reprinted Source: https://blog.csdn.net/qq_30100043/article/details/53391308

Guess you like

Origin www.cnblogs.com/itzlg/p/11300725.html