The original link

In ES6, we have a new operator, the expansion operator, which can reduce the number of our code, sometimes even have a very useful role, let’s take a few common examples, and through the example to understand the use of the expansion operator.

1. The use of apply

When we have the function of multiple variables, especially when we don’t know the number of variables), sometimes by variables stored in arrays, and through the call to perform functions, had launched after the operator to have the better way (after all, use the call need to manually specify this, very convenient sometimes not very accurate)

/ / the generalfunctiona(x, y, z) { } var args = [0, 1, 2]; a.apply(null, args); // Expand operator a(... args);Copy the code

Other than that it’s ok

// An indefinite number of arguments need to be passed in, with the last parameter being the value to be specifiedfunction b() { console.log(arguments.length); console.log(arguments[arguments.length -1]); } var args = [0, 1, 2]; b(... args, -2)Copy the code

In general, it gives multi-parameter function calls a new way and avoids scoping problems.

2. Use in arrays

Array merging

var a = [1, 2];
var b = [0, ...a, 3]
Copy the code

Array splitting

var [a, ...b] = [0, 1, 2];
console.log(b) // [1, 2]
Copy the code

Array copy

var a = [1, 2];
var b = [...a];
Copy the code

3. The use of objects here refers to objects like {a:1}, because arrays, functions are also a kind of object.

let{ x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 }; console.log(z) // {a: 3, b: 4}Copy the code

This is also useful in arguments to functions

function test(... args) { console.log(args); }test('wang'.'23'.'man');
Copy the code

Arguments is not an array, so you can’t manipulate arguments directly.

In addition, many Node callback functions return error as the first value. In fact, many interfaces are designed that way. We can easily separate error from other parameters

request.get('./demo', (e, ... data) => { console.log(e); console.log(data); })Copy the code

The use of extended operators in objects is not currently supported in ES6. This is still in the draft of ES7, but we can use Babel to handle it.

Write an example finally, in making this a library https://github.com/sindresorhus/pify is used to change the callback function to promise

const fs = require('fs');

const pify = function(fn) {
  return function(... args) {returnnew Promise((resolve) => { fn(... args, (... res) => { resolve(res); }}})}); // fs.readFile pify(fs.readFile)('./package.json'.'utf8').then(([err, data]) => {
	console.log(data);
})

// ajax
pify(request)('http://demo.api.com').then(([err, data]) => {
  console.log(data)
})

Copy the code