ES6 - 解构(数组和对象)
解构对象
/**
* 解构:快捷,方便
*
* 对象解构
*/
{
var expense = {
type: "es6",
amount: "45"
};
//1.ES5
// var type = expense.type;
// var amount = expense.amount;
// console.log(type, amount); //output: es6 45
//2.ES6
const { type, amount, abc } = expense;
console.log(type, amount, abc); //output: es6 45 undefined
}
{
var saveFiled = {
extension: "jpg",
name: "girl",
size: 14040
};
//ES5
function fileSammary1(file) {
return `${file.name}.${file.extension}的总大小是${file.size};`
}
//ES6
//名字不能变,位置可以乱
function fileSammary2({ name, size, extension }) {
return `${name}.${extension}的总大小是${size};`
}
console.log(fileSammary1(saveFiled)); //output: girl.jpg的总大小是14040;
console.log(fileSammary2(saveFiled)); //output: girl.jpg的总大小是14040;
}
练习1:
const course = {
name: 'es6',
price: 500,
tearcher: {
name: 'tss',
age: 36
}
}
const { name, price, tearcher } = course;
console.log(name, price, tearcher); //es6 500 {name: 'tss', age: 36}
对象里面有对象,然后有重名 name
const course = {
name: 'es6',
price: 500,
tearcher: {
name: 'tss',
age: 36
}
}
const {
name: courseName, //重名的情况重命名
price,
tearcher,
tearcher: { name, age }
} = course;
console.log(courseName, price, tearcher, name, age);
//es6 500 {name: 'tss', age: 36} tss 36
练习2:返回 sum 相加的值
//ES 5
// const sum = (arr) => {
// let result = 0;
// for (let index = 0; index < arr.length; index++) {
// result += arr[index];
// }
// console.log(result);
// }
//ES6
const sum = ([a,b,c]) => {
console.log(a+b+c);
}
sum([1, 2, 3])
解构数组
/**
* 解构:快捷,方便
*
* 数组解构
*/
/**
* 基础
*/
{
const names = ["Henry", "Bucky", "Emily"];
const [name1, name2, name3] = names;
console.log(name1, name2, name3);
//用对象接收,反数组个数
const { length } = names;
console.log(length); // 3
//结合张开运算符
const [name, ...rest1] = names;
console.log(name); // Henry
console.log(rest1); //(2) ["Bucky", "Emily"]
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo; // 1
bar; // 2
baz; // 3
}
/**
* 数组中的对象
*/
{
//对象数组
const people = [
{ name: "Henry", age: 20 },
{ name: "Bucky", age: 25 },
{ name: "Emily", age: 30 }
];
// ES5
//读取数据元素中的对象参数值
{
var age = people[0].age;
age; // 20
}
// ES6
{
//读取数组的元素
{
const [age1, , age] = people;
console.log(age1); // { name: "Henry", age: 20 },
console.log(age); // { name: "Emily", age: 30 }
}
//读取数组元素中的对象参数值
{
const [{ age }] = people;
console.log(age); // 20
const [{ age }, { age: age1 }] = people;
console.log(age); // 20
console.log(age1); // 25
}
}
//数组转化为对象
{
const points = [
[4, 5], [10, 20], [0, 100]
];
/**
* 期望数据格式:
* [
* {x:4,y:5},
* {x:10,y:20},
* {x:0,y:100}
* ]
*/
let newPoints = points.map(([x,y])=>{
//1.传入解构 [x,y] = [4,5]
//2.x = 4, y = 5
//3.return {x:x,y:y} 简写 return {x,y}
return {x,y};
})
console.log(newPoints);
}
}