此文章为意译并不是直译,可参考具体原文javascript
解构赋值是javascript中的一个表达式语法糖,帮助开发者将数组,对象属性解构出来而且直接赋值到具体变量上面。java
let a,b,rest; [a,b] = [10,20]; console.log(a);// 10, console.log(b);// 20; [a,b,...rest] = [10,20,30,40,50,60]; console.log(a); // 10 console.log(b); // 20 console.log(rest);// [30,40,50,60]
let a=10,b=20; [a,b]=[b,a]; console.log(a);// 20 console.log(b);// 10;
// 1. 从已有对数组中解构赋值 let foo = ['one','two','three']; let [a,b] = foo; console.log(a); console.log(b); // 2. 从字面量中解构赋值 let [a,b] = [1,2]; // 3. 在解构赋值对时候设置默认值 let [a=5, b=10] = [1]; console.log(a); // 输出:1 console.log(b); // 输出:10 // 4. 解构从函数返回对数组 function getArr(){ return [1,2] } let [a,b] = getArr(); // 5. 解构对时候,忽略特殊位置对值 let [a,,b] = [1,2,3]; // 所有忽略 [,,] = [1,2,3]; // 6. 解构对时候将数组的其余值赋值给变量 let [a,...b] = [1,2,3,4,5]; console.log(a);// 1 console.log(b);// [2,3,4,5]
// 1. 解构对象 let obj = {name:'hello',age:18}; let {name,age} = obj; console.log(name);// hello; console.log(age);// 18 // 2. 解构字面量对象 let name,age; ({name,age} = {name:'hello',age:18});// 结果和上面同样,注意,这里为何须要用`()`包裹起来呢? // 独立的写法 let {name,age} = {name:'hello',age:18}; // 3. 解构的时候,设置别名 let obj = {name:'hello',age:18}; let {name:nameA,age:ageA} = obj; console.log(nameA);// hello console.log(ageA);// 18 // 4. 设置默认值,这个和数组解构相似 let obj = {name:'hello',age:18}; let {name='tom',age=20,city='sh'}=obj; console.log(city);// sh // 5. 设置默认值,同时又设置别名 let obj = {n:'hello',age:18}; let {n:name='tom',age:a=19,city:c='sh'} = obj; console.log(name); // hello console.log(a); // 18 console.log(c); // sh // 6. 设置函数参数的默认值 function drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius = 25} = {}) { console.log(size, cords, radius); // do some chart drawing } drawES2015Chart({ cords: {x: 18, y: 30}, radius: 30 });
let data = { title:'objetAdnArray', list:[ { id:1, des:'第一个对象', proList:[] }, { id:2, des:'第二个对象', proList: [] } ] } let { title, list:[{id,des}] } = data; console.log(title); // objetAdnArray console.log(id); // 1 console.log(des); // 第一个对象
var people = [ { name: 'Mike Smith', family: { mother: 'Jane Smith', father: 'Harry Smith', sister: 'Samantha Smith' }, age: 35 }, { name: 'Tom Jones', family: { mother: 'Norah Jones', father: 'Richard Jones', brother: 'Howard Jones' }, age: 25 } ]; for (let {name: n, family: {father: f}} of people) { console.log('Name: ' + n + ', Father: ' + f); } // "Name: Mike Smith, Father: Harry Smith" // "Name: Tom Jones, Father: Richard Jones"
function userId({id}) { return id; } function whois({displayName, fullName: {firstName: name}}) { console.log(displayName + ' is ' + name); } var user = { id: 42, displayName: 'jdoe', fullName: { firstName: 'John', lastName: 'Doe' } }; console.log('userId: ' + userId(user)); // "userId: 42" whois(user); // "jdoe is John"
let key = 'z'; let {[key]:foo} = {z:'this is z'}; console.log(foo); // this is z // 注意,这个用户很相似对象字面量赋值的用法 let obj = { [key]:'hello' } obj.z // hello
总结:es6提供了许多语法糖,在客户端使用的时候须要经过进行编译才能运行,而在服务器端nodejs
已经很好的支持了node