es6 learning - "..." operator

The learning mainly comes from the tutorial of Mr. Ruan Yifeng. Invasion and deletion.

meaning

The spread operator (spread) is three dots ( ...). It's like the inverse of the rest parameter, turning an array into a comma-separated sequence of parameters.

Take a look at the difference:

1、

2. Function call

function add(x, y) {
  return x + y;
}
const numbers = [4, 38];
add(...numbers) 

If we usually pass parameters, we will definitely call add(numbers[0],numbers[1]) like this

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

Very flexible to use

Note that the spread operator can be placed in parentheses only when the function is called, otherwise an error will be reported.

(...[1, 2])
// Uncaught SyntaxError: Unexpected number

console.log((...[1, 2]))
// Uncaught SyntaxError: Unexpected number

console.log(...[1, 2])
// 1 2

! ! Alternative to the apply method of a function

Since the spread operator expands the array, there is no need for a applymethod to turn the array into a function parameter.

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

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

pushAdds an array to the end of another array with a function .

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

// ES6 的写法
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);

! Application of spread operator

(1) Copy the array

Arrays are composite data types. If you copy directly, you just copy the pointer to the underlying data structure, instead of cloning a brand new array.

const a1 = [1, 2];
const a2 = a1;

a2[0] = 2;
a1 // [2, 2]

In the above code, it is a2not a1a clone, but another pointer to the same data. Modifications a2will directly lead a1to changes.

ES5 can only use workarounds to copy arrays

const a1 = [1, 2];
const a2 = a1.concat();

a2[0] = 2;
a1 // [1, 2]

In the above code, a1a clone of the original array will be returned, and modification a2will not have any a1effect.

The spread operator provides a shorthand for copying an array.

const a1 = [1, 2];
// 写法一
const a2 = [...a1];
// 写法二
const [...a2] = a1;

(2) Merge arrays

The spread operator provides a new way of combining arrays.

const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];

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

// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]

However, these two methods are shallow copies, and you need to be careful when using them.

const a1 = [{ foo: 1 }];
const a2 = [{ bar: 2 }];

const a3 = a1.concat(a2);
const a4 = [...a1, ...a2];

a3[0] === a1[0] // true
a4[0] === a1[0] // true

 

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324219577&siteId=291194637