ECMAScript6: 解构赋值
来自CloudWiki
背景
在Javascripts中,我们经常需要从某个对象或数组中提取特定数据赋给变量,这种操作重复且无趣。
// 真实应用场景中,book对象通常是从服务器端得到的数据 /*let book = { title: "Vue无难事", isbn: "9787121362217", price: 98, category: { id: 1, name: "Web前端" } } // 提取对象中的数据赋给变量 let title = book.title; let isbn = book.isbn; let price = book.price; let category = book.category.name; // 提取数组中的数据赋给变量 let arr = [1, 2, 3]; let a = arr[0], b = arr[1], c=arr[2];
在ES6中,为对象和数组提供了解构功能,允许按照一定模式从对象和数组中提取值,对变量进行赋值。
对象解构
let book = { title: "Vue无难事", isbn: "9787121362217", price: 98 } let {title, isbn, price} = book; console.log(title); // Vue无难事 console.log(isbn); // 9787121362217 console.log(price); // 98*/
如果变量之前已经声明,那么需要用圆括号包裹整个解构赋值语句:
let book = { title: "Vue无难事", isbn: "9787121362217", price: 98 } let title, isbn, price; //{title, isbn, price} = book; // 语法错误 ({title, isbn, price} = book); // 正确*/
数组解构
let arr = [1, 2, 3]; let [a, b, c] = arr; console.log(a); //1 console.log(b); //2 console.log(c);
/*let arr = [1, 2, 3]; let a, b, c; [a, b, c] = arr; //OK console.log(c);*/ /*let arr = [1, 2, 3]; let [a, b, c, d = 0] = arr; console.log(d); //0*/