ES6(壹):方便的解構賦值

插個旗子🚩記念一番,這是ES6的第一篇文章( ̄︶ ̄)↗ 。javascript

ES6

ECMAScript是一種腳本語言的標準規範,ES6(ECMAScript)於2015正式發佈java

ECMAScript (or ES) is a scripting-language specification standardized by Ecma International in ECMA-262 and ISO/IEC 16262. It was created to standardize JavaScript, so as to foster multiple independent implementations. ——《維基百科》數組

什麼是解構賦值

ES6中,可使用數組和對象對變量賦值,叫作「解構賦值」。函數

解構賦值能夠分爲:數組的解構賦值、對象的解構賦值。ui

解構賦值清晰又簡潔,優雅又有效率。是不可多得的「賦值利器」。spa

使用說明書

數組的解構賦值

一一對應:

let arr =[1,2,5];
    let [a,b,c]=arr;
    console.log([a,b,c]);
複製代碼

對應關係是這樣滴:3d

若是數量不同?? :

let arr =[1,2,5,6];
    let [a,b,c]=arr;
    console.log([a,b,c]);
複製代碼

多餘的會被忽略掉code

let arr =[1,2];
    let [a,b,c]=arr;
    console.log([a,b,c]);
複製代碼

少的會undefinedcdn

甚至還能夠跳過:

let arr =[1,2,3];
    let [a,,c]=arr;
    console.log([a,,c]);
複製代碼

對應關係是這樣滴:對象

對象的解構賦值

一一對應:

let a={
        first:1,
        second:2
    }
    let {first,second}=a;
    console.log({first,second})
複製代碼

按屬性名的一一對應關係來賦值:

若是數量不同?? :

let a={
        first:1
    }
    let {first,second}=a;
    console.log({first,second})
複製代碼

找不到的屬性會undefined

若是鍵名不對應:

let a={
        one:1,
        two:2
    }
    let {first,second}=a;
    console.log({first,second})
複製代碼

若是鍵名不對應,沒法進行賦值

順序有影響嗎? :

let a={
        second:2,
        first:1
    }
    let {first,second}=a;
    console.log({first,second})
複製代碼

由於對象是元素的無序集合,因此順序有並無影響

能夠提供默認值

{first=10,second}

一些應用

交換兩個變量的值(無需第三個容器)

原來咱們若是要交換兩個變量的值,須要這麼搞:

let a=1;
    let b=2;
    
    let c;
    c=a;
    a=b;
    b=c;
    console.log(a);
    console.log(b);
複製代碼

呃,有效但頗爲繁瑣......

可是,有了解構賦值後:

let a=1;
    let b=2;
    
    [a,b]=[b,a]

    console.log(a);
    console.log(b);
複製代碼

嗯(滿意), 優雅~~

函數參數

原來咱們寫個函數,若是參數較多時,實參萬一寫錯一個,就一步錯,步步錯:

function f(a,c,b,d,e,f,g){
        console.log(a,b,c,d,e,f,g)
    }
    f("one","two","three","four","five","six","seven")
複製代碼

可是如今,咱們有了賦值利器——解構賦值:

function f({a,c,b,d,e,f,g}){
        console.log(a,b,c,d,e,f,g)
    }
    f({a:"one",b:"two",c:"three",d:"four",e:"five",f:"six",g:"seven"})
複製代碼

清晰明瞭,想出錯都難

嗯,優雅~~

解構賦值在實際中應用還有不少。。。。。。

結束

本文對解構賦值作了簡要總結,解構賦值應用普遍,本篇所述內容皮毛而已,但願有所幫助。

相關文章
相關標籤/搜索