深入理解es6中强大的【...】操作符

... 运算符, 是ES6里一个新引入的运算法, 也叫展开/收集运算符(也被叫做延展操作符 - spread operator),本篇文章讲解一下其具体的用法。

基础用法1:展开

const a = [2, 3, 4]
const b = [1, ...a, 5]
console.log(b);// [1, 2, 3, 4, 5]

基础用法2:收集

function foo(a, b, ...c) {
    console.log(a, b, c)
}
foo(1, 2, 3, 4, 5); // 1, 2, [3, 4, 5]

基础用法3:把类数组转换为数组

const nodeList = document.getElementsByClassName("test");
const array = [...nodeList];
  
console.log(nodeList); // HTMLCollection [ div.test, div.test ]
console.log(array); // Array [ div.test, div.test ]

使用 ... 就可以实现类数组到数组的转换, 转换之后, 就可以使用数组的各种方法了。那么这个操作符出来之前是如何转换的呢?见下面例子:

// es5
function bar() {
    var args = Array.prototype.slice.call(arguments);
    args.push(4, 5, 6);
    return args;
}
console.log(bar(1, 2, 3)); // [1, 2, 3, 4, 5, 6]
// es6
function foo(...args) {
    args.push(4, 5, 6);
    return args;
}
console.log(foo(1, 2, 3)); // [1, 2, 3, 4, 5, 6]

基础用法4:为数组新增成员

const peoples = ["jone", "jack"];
const mrFan = "吴亦凡";
const all = [...peoples, mrFan];
console.log(all); //  ["jone", "jack", "吴亦凡"]

基础用法5:为对象新增属性

const obj = { name: 'jack', age: 30 }
const result = { ...obj, sex: '男', height: '178cm' }
console.log(result); // {name: "jack", age: 30, sex: "男", height: "178CM"}

基础用法6:合并数组或数组对象

const a = [1, 2, 3];
const b = [4, 5, 6];
const result = [...a, ...b]; //  [1, 2, 3, 4, 5, 6] 

数组对象也一样

基础用法7:合并对象

const people = {
    name: 'Lucy',
    age: 30,
    sex: '女'
};
const base = {
    age: 22,
    job: 'teacher',
    height: '168cm'
}
const all = { ...people, ...base }; 
console.log(all); // {name: "Lucy", age: 22, sex: "女", job: "teacher", height: "168cm"}

注:相同的属性会覆盖掉

我是分割线

高级用法1:复制引用类型的数据

const people = {
    name: 'Lucy',
    age: 30,
    sex: '女',
    hobbies: ['play games', 'basketball', 'swim']
};
const result = { ...people, ...people.hobbies };
console.log(result); // {0: "play games", 1: "basketball", 2: "swim", name: "Lucy", age: 30, sex: "女", hobbies: Array(3)}

高级用法2:增加条件属性

例子1:

const people = {
    name: 'Lucy',
    age: 30,
    sex: '女',
    hobbies: ['play games', 'basketball', 'swim']
};
const attrs = ['basketball', 'swim']
const result = attrs ? { ...people, attrs } : people
console.log(result); // {name: "Lucy", age: 30, sex: "女", hobbies: Array(3), attrs: Array(2)}

例子2:

const people = {
    name: 'Lucy',
    age: 30,
    sex: '女',
    hobbies: ['play games', 'basketball', 'swim']
};
const attrs = ['basketball', 'swim']
const result = {
    ...people,
    ...(attrs && { attrs })
}
console.log(result); // {name: "Lucy", age: 30, sex: "女", hobbies: Array(3), attrs: Array(2)}

类似于给对象添加属性

高级用法3:默认结构和添加默认属性

默认解构:我们知道, 当结构一个对象的时候, 如果这个对象里没有某个属性, 解出来是undefined , 我们可以添加默认值来解决:

const people = {
    name: 'Lucy',
    age: 30,
};
let { name, age, sex = 'female' } = people;
console.log(name, age, sex); // Lucy 30 female
posted @ 2020-01-02 15:57  Jone_chen  阅读(2998)  评论(0编辑  收藏  举报