一、定义:
扩展运算符(spread)是三个点(…)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。
二、注意事项及特殊情况
1、不可用()括起来否则会报错,除非方法调用
2、如果将扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错const […aa, bb] = [1, 2,3];// 报错
3、扩展运算符内部调用的是数据结构的 Iterator 接口,因此只要具有 Iterator 接口的对象,都可以使用扩展运算符,比如 Map 和 Set 结构,Generator 函数
4、扩展运算符后面还可以放置表达式…(x > 0 ? [‘a’] : []),
5、如果扩展运算符后面是一个空数组,则不产生任何效果。[…[], 1] // [1]
三、应用
1、对象转成数组、字符串转成数组
[{...item.thread}]// 可以将item.thread一组对象转成数组———敲敲敲级好用的
[...'hello’]// [ "h", "e", "l", "l", "o" ]字符串转成数组
2、替代assign将对象合并(对象内容后面会替代前面的)
let bar = { a: 1, b: 2 };
let baz = Object.assign(bar,{ a: 2, b: 4 }); // {a: 2, b: 4}
let bar = {a: 1, b: 2};
let baz = {...bar, ...{a:2, b: 4}}; // {a: 2, b: 4}
3、替代concat方法将数组合并(合并数组)
const arr1 = ["a", "c"];
const arr2 = ["c"];
const arr3 = ["d", "e"];
// ES5 的合并数组
console.log(arr1.concat(arr2, arr3));// ["a", "c", "c", "d", "e"]
// 扩展运算符
console.log(...arr1,...arr2,...arr3);// a c c c d e
console.log([...arr1,...arr2,...arr3])// ["a", "c", "c", "d", "e"]
4、解构赋值
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 // []
5、数组去重、字符串去重
nums1 = [...new Set(nums1)]
item = [...new Set(item.split(''))].join('') // 现将Set内容转成数组,最后转回字符串
6、含有Iterator 接口的内置对象都可以使用扩展运算符便利
let map = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
let arr = [...map.keys()]; // [1, 2, 3]
const go = function*(){
yield 1;
yield 2;
yield 3;
};
[...go()] // [1, 2, 3]
四、参考
https://es6.ruanyifeng.com/?search=…&x=0&y=0#docs/array#%E6%89%A9%E5%B1%95%E8%BF%90%E7%AE%97%E7%AC%A6
https://blog.csdn.net/astonishqft/article/details/82899965