ES6 - 解构(数组和对象)
Posted tangge
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}
解构数组
/**
* 解构:快捷,方便
*
* 数组解构
*/
/**
* 基础
*/
{
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 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);
}
}
以上是关于ES6 - 解构(数组和对象)的主要内容,如果未能解决你的问题,请参考以下文章
三阶段课程——Day02(ES6简介let和const)(数据类型和数据结构:字符串扩展Symbol数组新增方法对象新增SetMap数组解构对象解构...运算符)