ES6 解构对象和数组
1.解构对象
let saveFiled = { extension: "jpg", name:"girl", size:14040 }; ES5 function fileSammary(file){ return `${file.name}.${file.extension}的总大小是${file.size}`; } console.log(fileSammary(saveFiled)); ES6 function fileSammary({name,extension,size}){ return `${name}.${extension}的总大小是${size}`; } console.log(fileSammary(saveFiled));
2.解构数组
1.返回数组第一位数值 const names = ["Henry","Bucky","Emily"]; ES5 console.log(names[0]) ES6 const [name1,name2,name3] = names; console.log(name1) 2.返回数组个数 ES5 console.log(names .length) ES6 const { length } = names console.log(length) 3.结合展开运算符 const [name,...rest] = names; console.log(name, rest); 4.对象数组 const people = [ {name:"Henry",age:20}, {name:"Bucky",age:25}, {name:"Emily",age:30} ]; ES5 var age = people[0].age; console.log(age); ES6 const [age] = people; console.log(age) //{name:"Henry",age:20} const [{age}] = people; console.log(age) // 20 5. 使用场景 将数组转化为对象 const points = [ [4, 5], [10, 1], [0, 40] ] // 期望数据格式 [ {x:4,y:5}, {x:10,y:1}, {x:0,y:40} ] ES6 let newPoints = points.map(pair => { // const x = pair[0]; // const y = pair[1]; const [x,y] = pair; return {x,y} }) let newPoints = points.map(([x, y]) => { // const x = pair[0]; // const y = pair[1]; // const [x,y] = pair; return { x, y } }) console.log(newPoints)