HLJ 发布于
2025-06-11 10:00:41
0阅读

JavaScript Rest 参数与 Spread 语法

上一篇文章:

JavaScript 递归与堆栈

JavaScript Rest 参数与 Spread 语法

Rest 参数(剩余参数)

Rest 参数允许你将不定数量的参数表示为一个数组。

基本语法

function sum(...numbers) {
  return numbers.reduce((acc, curr) => acc + curr, 0);
}

console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15

特点

  1. Rest 参数必须是函数参数的最后一个参数

    // 错误示例
    function fn(a, ...b, c) {} // SyntaxError
    
  2. Rest 参数与 arguments 对象的区别:

    • Rest 参数是真正的数组实例,可以使用数组方法
    • arguments 是类数组对象,需要转换为数组才能使用数组方法
  3. 可以与解构赋值一起使用

    const [first, ...rest] = [1, 2, 3, 4];
    console.log(first); // 1
    console.log(rest); // [2, 3, 4]
    

Spread 语法(展开语法)

Spread 语法允许一个可迭代对象(如数组或字符串)在需要多个参数或元素的地方展开。

基本用法

  1. 函数调用中的使用

    const numbers = [1, 2, 3];
    console.log(Math.max(...numbers)); // 3
    
  2. 数组字面量中的使用

    const arr1 = [1, 2, 3];
    const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
    
  3. 对象字面量中的使用 (ES2018+)

    const obj1 = { a: 1, b: 2 };
    const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
    

特点

  1. 可以用于浅拷贝数组或对象

    const original = [1, 2, 3];
    const copy = [...original];
    
  2. 可以合并多个数组或对象

    const arr1 = [1, 2];
    const arr2 = [3, 4];
    const merged = [...arr1, ...arr2]; // [1, 2, 3, 4]
    
  3. 可以将字符串转换为字符数组

    const str = "hello";
    const chars = [...str]; // ["h", "e", "l", "l", "o"]
    

Rest 参数 vs Spread 语法

特性 Rest 参数 Spread 语法
位置 函数参数定义时使用 函数调用或数组/对象字面量中使用
作用 将多个参数收集为数组 将数组/对象展开为多个元素
符号位置 在参数定义时使用 ... 在表达式或字面量中使用 ...
使用场景 函数参数处理 数组/对象操作、函数调用传参

实际应用示例

  1. 移除数组中的第一个元素

    const [first, ...rest] = [1, 2, 3, 4];
    console.log(rest); // [2, 3, 4]
    
  2. 合并对象并覆盖属性

    const defaults = { color: 'red', size: 'medium' };
    const userSettings = { color: 'blue' };
    const finalSettings = { ...defaults, ...userSettings }; // { color: 'blue', size: 'medium' }
    
  3. 将 NodeList 转换为数组

    const divs = [...document.querySelectorAll('div')];
    
  4. 函数柯里化

    function curry(fn) {
      return function curried(...args) {
        if (args.length >= fn.length) {
          return fn.apply(this, args);
        } else {
          return function(...args2) {
            return curried.apply(this, args.concat(args2));
          }
        }
      };
    }
    

掌握 Rest 参数和 Spread 语法可以大大简化 JavaScript 代码,使其更加简洁和易读。

当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2025-06-11/803.html
最后生成于 2025-06-13 20:52:59
上一篇文章:

JavaScript 递归与堆栈

此内容有帮助 ?
0