本文實例講述了ES6知識點整理之對象解構賦值應用。分享給大家供大家參考,具體如下:
ES6 允許按照一定模式,從數組和對象中提取值,對變量進行賦值,這被稱為解構(Destructuring), 在對象的解構賦值中有一些需要注意的事項
初識對象的解構
var {name} = { name:'Joh', age:10};console.log(name); // Joh
通過解構的形式取出對象中的屬性值
對解構出的屬性進行重命名
var {name} = { name:'Joh', age:10};console.log(name); // Joh
// 通過{屬性:新的名稱} = 對象的方式 對解構出的屬性進行重命名var {color:color2} = { color:'red', age:10};console.log(color2); // redconsole.log(color); // 此處報錯:Uncaught ReferenceError: color is not defined
對象嵌套解構中模式和變量的區別
var obj = { a:{ b:{ c:123 } }};let {a:{b:{c}}} = obj; // 針對嵌套解構的最終輸出只能是最里層的,外層的a和b都作為解構中的一種模式存在,而不是變量,只有c能正常輸出console.log(c); // 123console.log(a, b, c); // Uncaught ReferenceError: a is not defined 報錯之后停止
解析對象的默認值
var obj = { name:'Joh', age:22};var {name, id='999', age} = obj;console.log(name, id ,age); // Joh 999 22
var obj2 ={ name:'Lily', age:10};var {name:name2, id:id2='888', age:age2} = obj2;console.log(name2, id2, age2); // Lily 888 10
解構對象中可能出現的異常
① 父解構的節點為undefined,在編程中一定要注意這個,屬于粗心錯誤 :
let {x:{y}} = {name:{y:12}};// 父結構中沒有x屬性名, 錯誤:Cannot destructure property `y` of 'undefined' or 'null'.
② 事先定義了一個變量重名錯誤 :
let name;let {name} = {name:'Joh'};// Uncaught SyntaxError: Identifier 'name' has already been declared
解決方案1:
let name;let {name:name2} = {name:'Joh'};console.log(name2);//運行結果:Joh
解決方案2:
var name;var {name} = {name:'Joh'};console.log(name);//運行結果:Joh
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答