扩展运算与解构赋值

扩展运算

//对象扩展
args = {...obj,...obj}

//数组扩展
args = [...arr,...arr]

//函数赋值
function f(...values){
    console.log(values.length);
}
f(1,2);      //2
f(1,2,3,4);  //4
// ||
function f(x, y, z) {}
f(...[arr])

//去重
[...new Set(arr)]; // [1, 2, 3, 4]
[...new Set('ababbc')].join(''); // "abc" 字符串去重
  • 函数
function f(...values){
    console.log(values.length);
    const [a, b, c] = values
}
f(1,2);      //2
f(1,2,3,4);  //4
//不定参数用来表示不确定参数个数,具名参数只能放在参数组的最后,并且有且只有一个不定参数。
function addNumbers(x,y,z){
    return x+y+z;
}

var numbers = [1,2,3,4];
addNumbers(...numbers); //6
//函数调用中,扩展运算符(...)将一个数组,变为参数序列

解构赋值

//数组解构
var arr = [2, 'this is string', 4, 6]
var [a, b, c] = arr

//嵌套数组解构
var arr2 = [[1, 2, [3, 4]], 5, 6];
var [[d, e, [f, g]], h, i] = arr2
  • 改变对象属性名
var obj3 = {
    name: 'chris',
    sex: 'male',
    age: 26
};
var {name: nickname, age: howOld} = obj3  //改变对象属性名
console.log(nickname + ' ' + howOld); //chris 26
//解构重名
var obj6 = {
    name: 'AAAA',
    sex: 'ddd',
    age: 55,
    son: {
        name: '小父',
        sonSex: 'gay',
        sonAge: 27
    }
};
var {name: myName, son: {name, sex, age}} = obj6
console.log(myName)
console.log(name)
  • 对象多层解构
const info = {
  person: {
    name: 'xiaobe',
    other: {
      age: 22,
    }
  },
  song: 'rolling',
}
// 解构song
const { song } = info;

// 解构person的内容
const { person: { name, other: { age } } } = info;
//person和other是属于未定义的变量
  • 循环解构
//对象
var arr5 = [{name: '催催', age: 26}, {name: '笑笑', age: 27}, {name: '转转', age: 28}]
for (let {name, age} of arr5) {
    console.log(name + ' ' + age + ' ')
}
//数组
var arr6 = [[11, 12], [21, 22], [31, 32]]
for (let [a, b] of arr6) {
    console.log(a)
    console.log(b)
}

...扩展与解构赋值结合

  • 如果将扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错
//[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 // []  
原文地址:https://www.cnblogs.com/ajaemp/p/11905189.html