JavaScript 扩展运算符
JavaScript 扩展运算符 (…)
*它既可用于数组,也可用于对象,在数组中它的使用情况如下:
**1- 构建数组:**
const arr = [5, 6, 7]; // without the spread operator 😐 const badArr = [1, 2, 3, 4, arr[0], arr[1], arr[2]]; console.log(badArr); // [1, 2, 3, 4, 5, 6, 7] // with the spread operator 😃 const goodArr = [1, 2, 3, 4, ...arr]; console.log(goodArr); // [1, 2, 3, 4, 5, 6, 7]
console.log(...goodArr); // 1 2 3 4 5 6 7 //the line above is just like writing this code: console.log(1, 2, 3, 4, 5, 6, 7); // 1 2 3 4 5 6 7
const foods = ['chicken', 'meat', 'rice']; const Newfoods = [...foods, 'pizza ']; console.log(Newfoods); // ['chicken', 'meat', 'rice', 'pizza ']
console.log(foods); // ['chicken', 'meat', 'rice']
**扩展运算符与数组结合使用的两个有用用例:**
const arrOriginal = [1, 2, 3, 4, 5]; const arrCopy = [...arrOriginal]; console.log(arrCopy); // [1, 2, 3, 4, 5]
const arr1 = ['A', 'B', 'C']; const arr2 = ['D', 'E', 'F']; const mergedArr = [...arr1, ...arr2]; console.log(mergedArr); // ['A', 'B', 'C', 'D', 'E', 'F']
const str = 'spongeBob'; const letters = [...str, 'squarePants']; console.log(letters); // ['s', 'p', 'o', 'n', 'g', 'e', 'B', 'o', 'b', 'squarePants']
console.log(`spelling sponge bob's name: ${...str}`); // Expression expected
**2- 将参数传递给函数**
function orderDrink(drink1, drink2) { console.log(`Your Ordered drinks are ${drink1} and ${drink2}`); } const drinks = ['water', 'juice']; orderDrink(...drinks); // if you did it without the Spread Operator, it would be like this orderDrink(drinks[0], drinks[1]);
const restaurant = { name: 'spongeBob restaurant', location: 'Bikini bottom', chef: 'spongeBob', }; // adding new properties const restaurantNew = { ...restaurant, netWorth: 'billions' }; // making a copy const restaurantCopy = { ...restaurant };