react es6语法 之 “ ... ” ,扩展运算符

扩展运算符(…)用于取出参数对象中的所有可遍历属性,拷贝到当前对象之中

let bar = { a: 1, b: 2 };
let baz = { ...bar }; // { a: 1, b: 2 }

参考:https://blog.csdn.net/astonishqft/article/details/82899965

应用:

1、将数组转化为函数参数序列

function add(x, y) {
  return x + y;
}

const numbers = [4, 38];
add(...numbers) // 42

2、对数组进行值拷贝(直接用=是无法对数组进行值拷贝的,只能复制一份引用)

const arr1 = [1, 2];
const arr2 = [...arr1];

3、字符串转为字符数组

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

4、迭代器iterator接口转为数组

5、数组合成

first // 1 
rest // [2, 3, 4, 5]
const [first, ...rest] = [1, 2, 3, 4, 5]; 需要注意的一点是: 如果将扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错。 const [...rest, last] = [1, 2, 3, 4, 5]; // 报错 const [first, ...rest, last] = [1, 2, 3, 4, 5]; // 报错