02 ES6的函数参数默认值

函数参数的默认值是 ECMAScript 2015 (ES6) 引入的功能,它允许你在函数定义时为参数指定默认值。当函数被调用时,如果没有为某个参数提供值,或者提供了 undefined,那么就会使用这个默认值。

以下是函数参数默认值的一些关键点和用法示例:

基本用法

javascript 复制代码
function greet(name = 'Guest') {
  console.log(`Hello, ${name}!`);
}

greet();        // 输出 "Hello, Guest!" 因为没有提供 name 参数
greet('Alice'); // 输出 "Hello, Alice!" 使用提供的 name 参数

在这个例子中,如果调用 greet 函数时没有提供 name 参数,name 将默认为 'Guest'

参数列表中的默认值

默认值可以设置在参数列表的任意位置,但一旦参数有默认值,它右边的所有参数也必须有默认值。

javascript 复制代码
function greet(name, message = 'Hello') {
  console.log(`${message}, ${name}!`);
}

// 这将抛出错误,因为 message 有默认值,但 age 没有
// greet('Alice');

greet('Alice', 'Hi'); // 输出 "Hi, Alice!"
greet('Alice');       // 输出 "Hello, Alice!" 使用 message 的默认值

与解构赋值结合使用

默认值可以与解构赋值结合使用,为更复杂的参数结构提供默认值。

javascript 复制代码
function configure(options = {}) {
  console.log(`Width: ${options.width || 'default width'}`);
  console.log(`Height: ${options.height || 'default height'}`);
}

configure({ width: 100 }); // 输出 "Width: 100" 和 "Height: default height"
configure();               // 输出 "Width: default width" 和 "Height: default height"

默认值是一次求值的

参数的默认值表达式在函数定义时求值一次,而不是每次调用函数时。

javascript 复制代码
let defaultGreeting = 'Hello';

function greet(name, greeting = defaultGreeting) {
  console.log(`${greeting}, ${name}!`);
}

(defaultGreeting = 'Hi');
greet('Alice'); // 即使 defaultGreeting 已改变,依然输出 "Hello, Alice!"

函数的剩余参数

剩余参数(rest parameters)也可以用默认值。

javascript 复制代码
function sum(...numbers = []) {
  return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum());  // 输出 0,因为没有提供任何参数
console.log(sum(1)); // 输出 1
console.log(sum(1, 2, 3, 4)); // 输出 10

函数参数的默认值提供了一种方便的方式来定义函数,使得函数调用更加灵活和健壮。开发者可以根据需要提供参数,或者依赖预设的默认值。

相关推荐
Patrick_Wilson1 小时前
最佳实践是有保质期的:从一次 CDN external 白屏事故说起
前端·性能优化·前端工程化
YHHLAI1 小时前
[特殊字符] Agent 智能体开发实战 · 第一课:Tool Use —— 让大模型自动干活
前端·人工智能
nuIl1 小时前
我把 5 个编码 Agent 塞进了一个 npm 包
前端·agent·claude
L-影1 小时前
FastAPI 静态文件:Web 页面的“固定展柜”与“加速引擎”
前端·fastapi
陪我去看海2 小时前
受够了 AI 写完代码留下一堆端口?我做了一个端口管理App!
前端·macos·vibecoding
Xuepoo2 小时前
我抛弃了 DOM,但保留了无障碍访问
前端
李明卫杭州2 小时前
Vue2 vs Vue3 的 h 函数:渲染函数完整迁移指南
前端
月光刺眼2 小时前
用LangChain 打造第一个 Agent:LLM 大脑与 Tool 手脚的完整闭环
javascript·人工智能·全栈
星栈2 小时前
LiveView 的认证系统:从登录到权限,我一开始以为有 `current_user` 就算完事了
前端·前端框架·elixir
在因斯坦2 小时前
摸摸鱼之前端自己研究 Jenkins 自动化部署
前端