Object destructuring assignment

Object destructuring assignment
对象的解构赋值

let {name,age} = {name:'xx',age:9};
console.log(name, age);

let {A,B} = {name:'xx',age:9};
console.log(A, B);//->在对象的解构赋值中需要注意的是:赋值的变量需要和对象中的属性名吻合,否则无法获取对应的属性值 undefined*2
let {C=0} = {name:'xx',age:9};
console.log(C); // ->0 和数组的解构赋值一样,我们可以把后面不需要的获取的结构省略掉,而且也可以给当前的变量设置默认值
let {name} = {name:'xx',age:9};//=>xx
let {,age} = {name:'xx',age:9};//=>Uncaught SyntaxError:Unexpected token,和数组的解构赋值不一样的地方在于,对象前面不允许出现空来占位(因为对象获取需要通过具体的属性名获取,写成空的话,浏览器不知道怎么识别)

let {name,...arg} = {name:'xx',age:9,teacher:'xx'};
console.log(name,arg);//=>'xx'{age:9....} 支持拓展运算符的
//=>把对象进行浅克隆(只把第一级克隆了)
let obj = {name:'xxx',score : [100,90,80]};
let {...arg} = obj;
console.log(arg, obj);
console.log(arg === obj);//=>false
console.log(arg.score === obj.score); // ->true 浅克隆 不是深度克隆

//如何进行深度克隆

解构赋值的作用

Quickly swap the values ​​of two variables

let a = 12;
let b = 13;
[a,b] = [b,a];
//快速实现交换俩个变量的值
console.log(a, b); // 13 12
// let c = a;
// a = b;
// b = c;

Return multiple values ​​from a function

let fn = function () {
    let a = 12;
    let b = 13;
    let c = 14;
    return [a,b,c];
}
let [a,b,c] = fn();
console.log(a, b, c); //12 13 14

Can quickly accept multiple values ​​passed (I pass an array or object)

let fn = function ([A,B,C,D = 0]) {
    console.log(A, B, C,D);//12 23 34 0
};
fn([12,23,34]);
console.log(A);//A is not defined 函数中的A B C 是私有的变量

let fn = function ({x,y,z = 0}) {
    console.log(x, y, z);
};
fn({x:10,y:20});

Support for setting default values ​​for functions in ES6

let fn = function (x) {
    console.log(x); // undefined
    x = x ||0;
    console.log(x); // 0
};
fn();

let fn2 = function (x=0) {
    console.log(x); // 0
}
fn2();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326256335&siteId=291194637