ES6-解構

對象和數組是js中經常使用的數據解構,因爲JSON的普及,兩者已經成爲語言中特別重要的一個部分。ES6中添加了能夠簡化解析這種解構的新特性:解構。解構是一種打破數據結構,將其拆分紅更小部分的過程。node

在早期版本中,開發者爲了從對象和數組中獲取特定數據並賦值給變量,就像這樣:數組

var  = {
    name: 'tom',
    type: '1'
}
var name = node.name,    //tom
    type = node.type;    //1

對象解構

對象解構的語法是在賦值的左邊放置一個對象,例:數據結構

let node = {
    name:'tom',
    type: '1'
}

let {name, type} = node;

console.log(name, type)    //tom, 1

默認值

使用解構表達式時,若是指定的局部變量在對象中不存在,那麼這個局部變量會被賦值爲undefined,例:函數

let node = {
    name:'tom',
    type: '1'
}

let {name, type, value} = node;

console.log(name, type, value)    //tom, 1, undefined

這段代碼額外定義了一個局部變量value, 而後嘗試爲它賦值,然而在node對象上,並無對應名稱的屬性值,因此像預期中那樣賦值爲undefined.code

當指定的屬性不存在時,能夠定義一個默認值,在屬性名稱後面添加默認值便可, 例:對象

let node = {
    name:'tom',
    type: '1'
}

let {name, type, value='true'} = node;

console.log(name, type, value)    //tom, 1, true

爲變量value設置了默認值true,只有當node上沒有該屬性或者該屬性當值爲undefined時纔會生效。開發

爲非同名變量賦值

若你想使用不一樣的變量賦值,例:io

let node = {
    name:'tom',
    type: '1'
}

let {name, type:nameType, value='true'} = node;

console.log(name, nameType, value)    //tom, 1, true

在上面的代碼中,名稱被放置在右邊,須要進行值讀取的位置被放在左邊。console

嵌套對象的解構

對於深層次的解構,能夠深刻到嵌套對象的結構中去提取你想要的數據,例:function

let node = {
    name:'tom',
    type: '1',
    meat:{
        start:{
            date: '1980-01-23',
            time: '10:00'
        },
        end:{
            date: '1980-01-23',
            time: '11:00'
        }
    }
}

let {meat:{start}} = node;

console.log(start.time, start.date)    //11:00, 1980-01-23

還能更近一步,在對象的嵌套解構中爲本地變量使用不一樣的名稱,和爲非同名變量賦值語法相同。

數組解構

數組解構和對象解構很是類似,只是將對象替換成數組。數組解構時,解構做用在數組內部的位置上,而不是做用在對象的具體的屬性名稱上,例:

let colors = ['red', 'green', 'blue'];
let [firstColor, secondColor] = colors;
console.log(firstColor, secondColor)    //red, green

其餘的基本同樣不在一一列出。

混合解構

對象和數組解構能被用在一塊兒,以建立更復雜的解構表達式。在對象和數組混合解構中這麼作能更準確的提取出你想要的數據片斷。例:

let node = {
    name:'tom',
    type: '1',
    meat:{
        start:{
            date: '1980-01-23',
            time: '10:00'
        },
        end:{
            date: '1980-01-23',
            time: '11:00'
        }
    },
    colors: ['red', 'green', 'blue']
}

let {
    meat:{start},
    colors: [firstColor]
    } = node;

console.log(start.date, firstColor)    //1980-01-23, red

這種解構對從JOSN配置中抽取數據來講尤其有用。由於它不須要在探索整個結構。

參數解構

解構還有一個特別有用的場景, 即在傳遞函數參數時。 當一個js函數接收大量可選參數時,經常使用的模式是建立一個options對象,其中包含了附加的參數,就像這樣:

function foo(options) {
   var options = options || {}
   var name = options.name,
       tiem = options.time;
   
   //...其餘代碼
}

foo({
    name: 'tom',
    tiem: '10:00'
})

參數的解構提供了更清楚的地標標明瞭函數指望輸入的方案。它使用對象或數組解構的模式替代了具體的參數名稱。下面重寫了foo()函數:

function foo({name, time} = {}) {
   //...其餘代碼
}

foo({
    name: 'tom',
    tiem: '10:00'
})

參數解構擁有以上其它解構方式的全部能力。你能夠在其中使用默認參數、混合解構、或使用與屬性不一樣的其餘變量名。

相關文章
相關標籤/搜索