1、数组解析
// Data needed for first part of the section
const restaurant = {
name: 'Classico Italiano',
location: 'Via Angelo Tavanti 23, Firenze, Italy',
categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
mainMenu: ['Pizza', 'Pasta', 'Risotto'],
order: function (starterMenuIndex, mainMenuIndex) {
return [this.starterMenu[starterMenuIndex], this.mainMenu[mainMenuIndex]];
//返回数组
},
openingHours: {
thu: {
open: 12,
close: 22,
},
fri: {
open: 11,
close: 23,
},
sat: {
open: 0, // Open 24 hours
close: 24,
},
},
};
//array destructing 数组解析(拆包),把数组中的元素按顺序直接赋值给一个个变量,优先使用const类型变量
//格式: 以获取第一个、第三个元素为例子
//const [变量名, , 变量名] = arr 或者
//const [变量名 , , 变量名] = [xxx, xxx, xxx]
const [first, , secondary] = restaurant.categories;
console.log(first, secondary);
const [f1, s2] = restaurant.order(0, 1); //Focaccia, Pasta
console.log(f1, s2);
//当不知道数组的长度时,给变量初始化一个默认值,若该数组没有对应的元素(undefine),则该变量的值就是默认值
const [a = null, b = null, c = null] = ['hello', 'you'];
console.log(a, b, c);
//若是嵌套数组,需要完全解析,则变量也写成嵌套数组形式:
const [i, j] = ['hello', ['you', 'world']];
console.log(i, j);
const [k, [p, h]] = ['hello', ['you', 'world']];
console.log(k, p, h);
数组解析还可用于交换变量(仅let类型可交换变量):
//交换变量
let [main, second] = ['hello', 'world'];
[second, main] = [main, second];
console.log(main, second);
// const temp = main;
// main = second;
// second = temp;
二、 对象解析
/* 对象解析:直接根据属性名取属性,不需要按照顺序,对象属性本来也没有顺序 */
//格式:const { 属性名:重命名 = 默认值, 属性名 = 默认值, 属性名} = 对象名
//包含:重命名,默认值
const {
name: restaurantName = null,
openingHours = null,
starterMenu: starter = [],
} = restaurant;
console.log(restaurantName, openingHours, starter);
//mutating variables,与数组解析的交换变量的区别,需加上( ):
let a = 111;
let b = 222;
const obj = { a: 2, b: 7, c: 10 };
({ a, b } = obj); //需加上括号,因为{}花括号的js特性
console.log(a, b); //输出 2, 7
//嵌套对象的解析
const {fri:{open, close}} = restaurant.openingHours;
console.log(`friday wiill open from ${open} to ${close}`);
2、利用对象解析传参
//给餐馆对象增加一个方法:
//使用对象解析传参的好处:
//1.只需保证参数名和传过来的对象里的属性名一致即可,无需在意参数顺序
//2.只需传递一个参数(一个对象),而不需手动解析出属性再传多个参数
//别忘了对象解析的语法{ } = obj
orderDelivery: function ({ //
starterMenuIndex = 1,
mainMenuIndex = 1,
address = 'beijing',
deliveryTime = '22:30',
}) {
console.log(`${this.starterMenu[starterMenuIndex]} and ${this.mainMenu[mainMenuIndex]} will be delivered
to ${address} at ${deliveryTime}!`);
},
};
//调用方法,直接传递对象
restaurant.orderDelivery({
deliveryTime: '22:30',
address: 'shanghai',
starterMenuIndex: 1,
mainMenuIndex: 2,
});