假如我们有一个数组:
const arr = [7,8,9];
● 我们如果想要数组中的元素,我们必须一个一个手动的去获取,如下:
const arr = [7,8,9];
const badNewArr = [5, 6, arr[0], arr[1],arr[2]];
console.log(badNewArr);
● 但是通过展开运算符就非常的方便
const arr = [7,8,9];
const badNewArr = [5, 6, arr[0], arr[1],arr[2]];
console.log(badNewArr);
const newArr = [5,6,...arr];
console.log(newArr);
● 当然,我们也可以通过展开运算符提取数组中的所有数据
console.log(...newArr);
● 还记得我们之前的对象么,如下所示
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 (starterIndex, mainIndex) {
return [
restaurant.starterMenu[starterIndex],
restaurant.mainMenu[mainIndex],
];
},
oderDelivery: function({starterIndex = 1, mainIndex = 0, time='20:00',address,}) {
console.log(`Order received! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be delivered to ${address} at ${time}`);
},
};
● 例如现在我们现在菜单有所改变,我们在原来的基础上新增一个菜
const newMenu = [...restaurant.mainMenu, 'Gnocci'];
console.log(newMenu);
这样看起来展开运算符和解构是不是非常的相似;
解构和展开运算符是JavaScript中两种常用的操作符,它们在使用方式和功能上有一些区别。
const mainMenuCopy = [...restaurant.mainMenu];
const menu = [...restaurant.starterMenu,...restaurant.mainMenu];
console.log(menu);
const str = 'Jonas';
const letters = [...str, ' ', 'S.'];
console.log(letters);
● 例如我们在对象中添加一段函数来读取意大利面的配料
orderPasta: function(ing1,ing2,ing3) {
console.log(`Here is your declicious pasta with ${ing1},${ing2},${ing3}`);
}
● 接着我们来通过弹窗的方式来获取配料
const ingredients = [
prompt("Let's make pasta! Ingredient 1?"),
prompt('Ingredient 2?'),
prompt('Ingredient 3?'),
];
console.log(ingredients);
● 然后我们可以通过展开运算符来传参数到函数中
restaurant.orderPasta(...ingredients)
● 对象的浅拷贝
const newRestaurant = { foundedIn: 1998, ...restaurant, founder: 'Guiseppe'};
console.log(newRestaurant);
● 但是这种拷贝是浅拷贝,不是深度拷贝
const restaurantCopy = { ...restaurant};
restaurantCopy.name = 'Ristorante Roma';
console.log(restaurant.name);
console.log(restaurantCopy.name);