Array-Destructure數組
Object-Destructure學習
解構賦值:
使用數組索引去使用變量,不如直接賦值一個變量,可是也不適合用let聲明不少變量spa
let arr = ['hello', 'world'] // 經過索引訪問值 let firstName = arr[0] let surName = arr[1] console.log(firstName, surName) // hello world
ES6rest
let arr = ['hello', 'world'] let [firstName, surName] = arr console.log(firstName, surName) //hello world
//跳過某個值 //Array let arr = ['a', 'b', 'c', 'd'] let [firstName,, thirdName] = arr // 左邊是變量,右邊是一個可遍歷的對象,包括Set和Map console.log(firstName, thirdName) // a c //String let str = 'abcd' let [,, thirdName] = str console.log(thirdName) // c //Set let [firstName,, thirdName] = new Set([a, b, c, d]) console.log(firstName, thirdName) // a c
給對象屬性從新命名code
let user = { name: 's', surname: 't' }; [user.name,user.surname] = [1,2] //花括號和中括號之間必需要有分號 console.log(user) // { name: 1,surname: 2}
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] let [firstName,, thirdName,...last] = arr console.log(firstName, thirdName, last) // 1 2 [3, 4, 5, 6, 7, 8, 9] // 上面若是隻賦值firstName和thirdName,那麼剩下的參數arr會被回收掉,若是不想3-9的元素被刪掉,那麼能夠用[...rest] // rest只能在最後一個元素中使用
從前日後沒有取到爲undefined對象
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] let [firstName,, thirdName,...last] = arr console.log(firstName, thirdName, last) // 1 2 [3, 4, 5, 6, 7, 8, 9] let arr = [1, 2, 3] let [firstName,, thirdName,...last] = arr // 1 2 [3] let arr = [1, 2] let [firstName,, thirdName,...last] = arr // 1 2 [] let arr = [1] let [firstName,, thirdName,...last] = arr // 1 undefined [] let arr = [] let [firstName,, thirdName,...last] = arr // undefined undefined [] //默認沒有參數,會爲undefined,若是這個時候進行數字運算的時候,就會有問題 //若是避免這種狀況,就要進行默認值的賦值 let arr = [] let [firstName = 'hello',, thirdName,...last] = arr // hello undefined []
let options = { title: 'menu', width: 100, height: 200 } let { title, width, height } = options console.log(title, width, height) // menu 100 200
若是有變量衝突怎麼辦?不能用簡寫形式blog
// 下面title是匹配屬性名提取變量名稱 // title2是新的變量名 let {title: title2, width, height} = options console.log(title2, width, height) // menu 100 200
let options = { title: 'menu', height: 200 } let {title: title2, width = 130, height} = options console.log(title2, width, height) // menu 130 200
let options = { title: 'menu', width: 100, height: 200 } let { title, ...last } = options console.log(title, last) //menu {width: 100, height: 200}
let options = { size: { width: 100, height: 200 }, item: ['Cake', 'Donut'], extra: true } let { size: { width: width2, height }, item: [item1] } = options console.log(width2, height, item1) //100 200 "Cake"