對象的解構賦值(能夠不按順序,可是key必須同樣不然爲undefined)spa
//demo1 var {name,age} = { name: "Jewave", age:26 }; console.log(name); //'jewave' console.log(age); //26 //demo2 var {id,name,age} = { name: "Jewave", age:26,id:007 }; console.log(name); //'jewave' console.log(age); //26 console.log(id) //7 //demo3 var { id: personId, name: personName, age: personAge } = { name: "Jewave", age:26,id:007 }; console.log(personId); //7 console.log(personName); //'jewave' console.log(personAge); //26 //demo4 let object = { first: 'Hello', last: 'World' }; let { first: firstName, last: lastName } = object; console.log(firstName); //Hello console.log(lastName); //World
對象解構默認值的條件(對象屬性值嚴格等於undefined,也就是未定義)code
//demo1 var { x = 3 } = {}; console.log(x); //3 //demo2 var { x, y = 5 } = { x: 1 }; console.log(x); //1 console.log(y); //5 //demo3 var { message: msg = "You Are A Person!" } = {}; consle.log(msg); //"You Are A Person!" //demo4 var { x = 3 } = { x: undefined }; console.log(x); //3 //demo5 var { y = 3 } = { y: null }; console.log(y);//null
已聲明變量的解構賦值對象
var x; {x} = { x: 1 }; // Uncaught SyntaxError: Unexpected token = 爲啥報錯,由於{x}被理解成代碼塊而不是對象因此不能進行解構, 這時候咱們用一個括號將總體括起來就能夠。 var x; ({x} = { x: 1 }); console.log(x); //1
現有對象的方法blog
console.log( Math.sin(Math.PI/6) ); //0.49999999999999994 //簡化版的寫法可讀性更棒 let { sin, cos, tan, cot, PI } = Math; console.log( PI ); //3.141592653589793 console.log( sin(PI/6) ); //0.49999999999999994