返回
探索 ES2018 和 ES2019 中的 Rest/Spread 属性
前端
2024-02-07 00:20:21
在 ES2018 和 ES2019 中,引入了一种新的语法,称为 Rest/Spread 属性,可用于在对象和数组中轻松展开和收集元素。
Rest 操作符(...)
Rest 操作符(...)可以用于以下两个地方:
- 在对象解构模式中:
Rest 操作符(...)可以用来收集源对象中未被匹配的剩余属性。例如:
const person = {
name: "John",
age: 30,
city: "New York",
};
const { name, ...rest } = person;
console.log(name); // John
console.log(rest); // { age: 30, city: "New York" }
- 在数组解构模式中:
Rest 操作符(...)可以用来收集源数组中剩余的元素。例如:
const numbers = [1, 2, 3, 4, 5, 6];
const [first, ...rest] = numbers;
console.log(first); // 1
console.log(rest); // [2, 3, 4, 5, 6]
- 在函数参数中:
Rest 操作符(...)可以用来收集函数参数中的剩余参数。例如:
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15
Spread 操作符(...)
Spread 操作符(...)可以用于以下两个地方:
- 在对象字面量中:
Spread 操作符(...)可以用来将一个对象的所有可枚举属性展开到另一个对象中。例如:
const person1 = {
name: "John",
age: 30,
};
const person2 = {
...person1,
city: "New York",
};
console.log(person2); // { name: "John", age: 30, city: "New York" }
- 在数组字面量中:
Spread 操作符(...)可以用来将一个数组的所有元素展开到另一个数组中。例如:
const numbers1 = [1, 2, 3];
const numbers2 = [...numbers1, 4, 5, 6];
console.log(numbers2); // [1, 2, 3, 4, 5, 6]
- 在函数调用中:
Spread 操作符(...)可以用来将一个数组的所有元素展开到函数参数中。例如:
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
const numbers = [1, 2, 3, 4, 5];
console.log(sum(...numbers)); // 15
Rest/Spread 属性是 ES2018 和 ES2019 中引入的两种非常强大的语法,它们可以大大简化对象的解构和展开操作。如果你还没有使用过它们,我强烈建议你学习一下,它们肯定会让你受益匪浅。