"Code tailor",爲前端開發者提供技術相關資訊以及系列基礎文章,微信關注「小和山的菜鳥們」公衆號,及時獲取最新文章。
在開始學習以前,咱們想要告訴您的是,本文章是對阮一峯《ECMAScript6 入門》一書中 "變量的解構賦值" 章節的總結,若是您已掌握下面知識事項,則可跳過此環節直接進入題目練習javascript
若是您對某些部分有些遺忘,👇🏻 已經爲您準備好了!前端
變量的解構賦值的學習java
解構賦值語法是一種 Javascript 表達式。經過解構賦值, 能夠將屬性(值)從對象(數組)中取出,賦值給其餘變量。
// ES5,爲變量賦值,只能直接指定值 let a = 1 let b = 2 let c = 3 //ES6,容許這樣 let [a, b, c] = [1, 2, 3] //表示能夠從數組中提取值,按照對應位置,對變量賦值。
本質上,這種寫法屬於「模式匹配」,只要等號兩邊的模式相同,左邊的變量就會被賦予對應的值。
let [foo] = [] let [bar, foo] = [1]
let [x, y] = [1, 2, 3] x // 1 y // 2 let [a, [b], d] = [1, [2, 3], 4] a // 1 b // 2 d // 4
// 報錯 let [foo] = 1 let [foo] = false let [foo] = NaN let [foo] = undefined let [foo] = null let [foo] = {}
事實上,只要某種數據結構具備 Iterator 接口,均可以採用數組形式的解構賦值。
數組的元素是按次序排列的,變量的取值由它的位置決定;而對象的屬性沒有次序,變量必須與屬性同名,才能取到正確的值。
let { bar, foo } = { foo: 'aaa', bar: 'bbb' } foo // "aaa" bar // "bbb" let { baz } = { foo: 'aaa', bar: 'bbb' } baz // undefined
等號左邊的兩個變量的次序,與等號右邊兩個同名屬性的次序不一致,可是對取值徹底沒有影響。第二個例子的變量沒有對應的同名屬性,致使取不到值,最後等於 undefined。es6
let { foo } = { bar: 'baz' } foo // undefined
let obj = { p: ['Hello', { y: 'World' }], } let { p: [x, { y }], } = obj x // "Hello" y // "World"
字符串也能夠解構賦值。這是由於此時,字符串被轉換成了一個相似數組的對象。
const [a, b, c, d, e] = 'hello' a // "h" b // "e" c // "l" d // "l" e // "o"
相似數組的對象都有一個 length 屬性,所以還能夠對這個屬性解構賦值。
let { length: len } = 'hello' len // 5
解構賦值時,若是等號右邊是數值和布爾值,則會先轉爲對象。
let { toString: s } = 123 s === Number.prototype.toString // true let { toString: s } = true s === Boolean.prototype.toString // true
add
的參數表面上是一個數組,但在傳入參數的那一刻,數組參數就被解構成變量x
和y
function add([x, y]) { return x + y } add([1, 2]) // 3
function move({ x = 0, y = 0 } = {}) { return [x, y] } move({ x: 3, y: 8 }) // [3, 8] move({ x: 3 }) // [3, 0] move({}) // [0, 0] move() // [0, 0]
一:如下代碼輸出結果爲()數組
let obj = { a: 1, b: 2, c: { d: { e: 5 } } } let { a, b, c: { d }, } = obj console.log(d) // ?
Answer: {e: 5}微信
對象經過解構賦值展開,這裏用到了對象解構賦值的多層嵌套 因此 c 對應的解構是 obj 對象中的 {d: {e: 5}} ,而 c 對象中包含的 d 對應的解構就應該是 obj 中 c 裏面的 d,因此是{e: 5}.數據結構
二:如下程序解構賦值後各個變量的值爲 ( )函數
const [a, b, c, d, e] = [1, 2, 'a', 'c']
Answer:學習
console.log(a) //1 console.log(b) //2 console.log(c) //'a' console.log(d) //'c' console.log(e) //undefined
undefined
三:如下代碼的輸出結果爲()prototype
function drawES2015Chart({ size = 'big', cords = { x: 0, y: 0 }, radius = 25 } = {}) { console.log(size, cords, radius) } drawES2015Chart() drawES2015Chart({ size: 'small', cords: { a: 1 }, radius: { b: 1 } })
Answer:
'big',{x:0, y:0},25 ‘small', {a: 1}, {b:1}
drawES2015Chart() :
drawES2015Chart()
中沒有傳入參數,因此使用的是函數中的默認值 size
的默認值是 'big' ,cords
的默認值是{x:0, y:0},radius
的默認值是 25 drawES2015Chart({size: 'small', cords: {a: 1}, radius: {b: 1}}):
drawES2015Chart({size: 'small', cords: {a: 1}, radius: {b: 1}}) 中傳入了值,因此不使用默認值,size 的值被 'small' 替代,cords 的值變成 {a: 1} ,radius 的值變成 {b: 1}