ES6_扩展运算符

153 阅读1分钟

扩展运算符

扩展运算符具有spreed(展开)和rest(收集)功能

对数组而言就可以展开也可以收集

对对象而言只可以展开

一、对数组展开 ( ES6 )

可以展开数组放在函数参数中

可以克隆数组:

arr1 = [...arr2]

arr1 = [...arr2, 1];

二、对对象展开 ( ES7 )

const obj1 = {
    name: 'gyq',
    age: 18
}

// 克隆:
const obj2 = {
    ...obj1
}

// 克隆并覆盖:
const obj2 = {
    ...obj1,
    name: 'abc'    // 属性名重复,覆盖之前的
}

// 对象里面的对象和数组为浅克隆:
const obj1 = {
    name: 'gyq',
    age: 18,
    loves: ['a', 'b'],
    address; {
        name: 'nanjing',
        loc: 'jiangsu'
    }
}
const obj2 = {
    ...obj1
}
console.log(obj1 === obj2)  // false
console.log(obj1.loves === obj2.loves)      // true
console.log(obj1.address === obj2.address)  // true

// 克隆后,在原来的基础上增加
const obj2 = {
    ...obj1,
    loves: [...obj1.loves, 'c'],
    address: {
        ...obj1.address,
        key: 'jinlin'
    }
}

三、小练习

函数柯里化:

用户固化某个函数的前面的参数,得到一个新的函数,新的函数调用时,接收剩余的参数

function curry(func, ...args) {
    return function(...subArgs) {
        const allArgs = [...args, ...subArgs];
        if (allArgs.length >= func.length) {    // 参数够了
            return func(...allargs);
        } else {    // 参数不够,继续固化
            return curry(func, ...allArgs);
        }
    }
}