ES6扩展运算符的常用场景

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

1、复制数组或者对象
此方法只能是第一层数据的拷贝,多层数据该方法失效,因为是浅拷贝

const a2 = [...a1];
const obj2 = {...obj1}

深拷贝有

let b = JSON.parse(JSON.stringify(a));
//第三方插件lodash的方法
let b = _.cloneDeep(a);

2、数组的合并

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' ]

3、解构赋值

// 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   // []
posted @ 2022-11-04 08:49  SultanST  阅读(18)  评论(0编辑  收藏  举报