ES6學習之變量的解構賦值
阿新 • • 發佈:2017-10-26
iter 內部使用 位置 fine 嚴格 true red 組成 個數
1.數組的解構賦值
let [a, b, c] = ["hello", 1, 2] console.log(a) //hello console.log(b) //1 console.log(c) //2
本質上,這種寫法屬於“模式匹配”,只要等號兩邊的模式相同,左邊的變量就會被賦予對應的值。如果解構不成功,變量的值就等於undefined
。
let [, , third, last, ...rest] = ["foo", "bar", "baz"]; console.log(third) //baz console.log(last) //undefined console.log(rest) //[]
//不完全解構 let [a, b] = ["x", "y", "z"] console.log(a) //x console.log(b) //y //set結構解構 let [c, d] = new Set(["x", "y", "z"]); console.log(c) //x console.log(d) //y
只要某種數據結構具有 Iterator 接口,都可以采用數組形式的解構賦值。
設置默認值:ES6 內部使用嚴格相等運算符(===
),判斷一個位置是否有值。所以,如果一個數組成員不嚴格等於undefined
,默認值是不會生效的。
let [a = 1] = [undefined]; console.log(a);//1 let [b = 2] = [null]; console.log(b) //null
2.對象的解構賦值:對象的屬性沒有次序,變量必須與屬性同名,才能取到正確的值。若變量沒有對應的同名屬性,則賦值為undefined
。
let {name,age} = {name:"fred",age:20}; console.log(name) //fred console.log(age) //20 let {height}={name:"fred",age:20}; console.log(height) //undefined
變量名與屬性名不一致寫法:
let {name:person} = {name:"fred",age:20} console.log(person)//fred console.log(name) //ReferenceError: name is not defined
註:name是匹配模式,person才是變量,真正被賦值的是name
設置默認值:默認值生效的條件是,對象的屬性值嚴格等於undefined
let {name = "fred"} = {name:undefined} console.log(name) //fred let {age = 20} = {age:null} console.log(age) //null
為已聲明的變量賦值:
let x; {x} = {x:1} //SyntaxError: Unexpected token = //因為 JavaScript 引擎會將{x}理解成一個代碼塊 ({x} = {x:1}) //x=1
為變量賦值方法:
let {sin,cos} = Math; console.log(sin) //[Function: sin]
數組進行對象屬性的解構
let arr = [1,2,3] let {0:first,[arr.length-1]:last} = arr; console.log(first) //1 console.log(last) //3
3.字符串的解構賦值
const [a,b,c,d] = "hello"; //具有Iterator接口,采用數組形式的解構賦值 console.log(a) //h console.log(b) //e console.log(c) //l console.log(d) //l const {length:len} = "hello"; //字符串屬性的解構 console.log(len) //5
4.數值和布爾值的解構賦值
let {toString:value} = 123; console.log(value); //[Function: toString] let {toString:s} = true; console.log(s) //[Function: toString]
5.用途
交換變量的值
let a = 10; let b = 20; [a,b] = [b,a]; console.log(a) //20 console.log(b) //10
從函數返回多個值
// 數組 function test1(){ return [1,2,3] } let [a,b] = test1(); console.log(a) //1 console.log(b) //2 // 對象 function test2(){ return {a:20,b:40} } let {a:x,b:y} = test2(); console.log(x) //20 console.log(y) //40
函數參數的定義
// 參數是一組有次序的值 function f([x, y, z]) { ... } f([1, 2, 3]); // 參數是一組無次序的值 function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1});
提取JSON數據
let jsonData = { name:"fred", age:20 } let {name,age} = jsonData; console.log(name,age)
設置函數參數默認值
function person({name ="fred",age=20}){ }
遍歷Map結構
const map = new Map(); map.set("name","fred"); map.set("age",20); for(let [key,value] of map){ console.log(key + "is" + value) } // name is fred // age is 20
輸入模塊的指定方法
const { SourceMapConsumer, SourceNode } = require("source-map");
ES6學習之變量的解構賦值