Spread / REST
一句话解释
... 语法 是 'spread' 当 它 expands iterable 到 individual 元素, and 'REST' 当 它 collects 多个 元素 到 数组.
用大白话说
... syntax has two roles depending on context. As the spread operator, it expands an iterable (array, string) into individual elements. As the rest parameter, it collects multiple arguments into a single array.
Spread is used in array literals ([...arr1, ...arr2]), object literals ({ ...obj1, ...obj2 }), and function calls (fn(...args)). It creates shallow copies and merges collections.
Rest parameters are used in function declarations to collect remaining arguments: 函数 fn(首先, ...REST) puts all arguments after the first into an array called REST. This replaces the old 实参 object with a real array.
示例
// Spread
const a = [1, 2];
const b = [...a, 3]; // [1, 2, 3]
// Rest
function sum(...nums) {
return nums.reduce((x, y) => x + y, 0);
}
console.log(sum(1, 2, 3)); // 6Spread expands 数组; REST collects 实参 到 数组.
常见混淆
容易混淆的对象: REST
关键区别: Spread expands iterable 到 元素 (used in calls and literals); REST collects 元素 到 数组 (used in 函数 参数). 相同 语法, 不同 role based on 上下文.
相关术语
相关资源
相关课程
- 数组
学习 关于 spread.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。