ES6 中的解构数组和对象
1. 解构对象
var people = { name:'jarry', age:15 } const {name,age} = people; console.log(name,age) //jarry 15
//例子
function who({name,age}){ return `${name}的年龄是${age}`; } console.log(who(people)) //jarry的年龄是15
2.解构数组
var names = ["tom","jarry","jack"] //返回数组元素 const [name1,name2,name3] = names; console.log(name1,name2,name3) //tom jarry jack // 返回数组个数 const {length} = names; console.log(length) // 3 // 结合展开运算符 const [name,...rest] = names console.log(name) // tom console.log(...rest) // jarry jack
3.应用场景
// 将二维数组转为数组对象 var points = [ [2,3], [10,5], [7,2] ] let newPoints = points.map(([x,y]) => { return {x,y} }) console.log(newPoints) // [{x: 2, y: 3},{x: 10, y: 5},{x: 7, y: 2}]