当前位置: 首页 > news >正文

【ES6新特性】默认参数常见用法

ES6新特性之默认参数的多种用法

🚀默认参数基础用法

在ES6中,我们可以直接在函数参数列表中为参数设置默认值:

// ES5的实现方式
function greet(name) {
  name = name || 'Guest';
  console.log(`Hello, ${name}!`);
}

// ES6默认参数写法
function greet(name = 'Guest') {
  console.log(`Hello, ${name}!`);
}

greet(); // Hello, Guest!
greet('Alice'); // Hello, Alice!

特性说明:

  • 默认值仅在参数为undefined时生效
  • null会被认为是一个有效值,不会触发默认值
  • 默认参数可以是任意表达式

🚀默认参数的进阶用法

1. 结合解构赋值

// 对象解构默认值
function setOptions({ 
  width = 100, 
  height = 200, 
  color = '#fff' 
} = {}) {
  console.log(width, height, color);
}

setOptions({ width: 500 }); // 500 200 #fff
setOptions(); // 100 200 #fff

// 数组解构默认值
function getFirst([firstItem = 0] = []) {
  return firstItem;
}

2. 后置参数默认值

function createElement(tag = 'div', content) {
  const elem = document.createElement(tag);
  elem.textContent = content;
  return elem;
}

// 必须显式传递undefined才能使用默认值
const div = createElement(undefined, 'Hello');

3. 动态默认值

function generateId(prefix = 'id', random = Math.random().toString(36).slice(2)) {
  return `${prefix}_${random}`;
}

console.log(generateId()); // id_1a2b3c
console.log(generateId('user')); // user_4d5e6f

🚀默认参数的作用域

1. 参数顺序依赖

function tricky(a = 1, b = a * 2) {
  console.log(a, b);
}

tricky();     // 1 2
tricky(3);    // 3 6
tricky(2, 4); // 2 4

2. 暂时性死区(TDZ)

function example(a = b, b = 2) {
  // ❌ 错误:Cannot access 'b' before initialization
}

function validExample(a = 2, b = a * 3) {
  // ✅ 正确
}

🚀实际应用场景

1. 配置项合并

function initPlugin(options = {}) {
  const defaults = {
    debug: false,
    maxRetry: 3,
    timeout: 5000
  };

  return { ...defaults, ...options };
}

2. API请求参数处理

async function fetchData({
  url = '/api/data',
  method = 'GET',
  headers = { 'Content-Type': 'application/json' }
} = {}) {
  try {
    const response = await fetch(url, { method, headers });
    return response.json();
  } catch (error) {
    console.error('Request failed:', error);
  }
}

🚀注意事项

  1. 箭头函数的默认参数:
const multiply = (a = 1, b = 1) => a * b;
  1. 默认参数不计入函数length属性:
function demo(a, b = 1, c) {}
console.log(demo.length); // 1
  1. 默认值表达式在每次调用时重新计算:
function getTime(now = Date.now()) {
  return now;
}

console.log(getTime() === getTime()); // false

相关文章:

  • (C语言)斐波那契数列(递归求解)
  • uniapp-x vue 特性
  • 通过 API 将Deepseek响应流式内容输出到前端
  • 论文精度:Transformers without Normalization
  • 提示词模板
  • KNN算法性能优化技巧与实战案例
  • vuex持久化存储,手动保存到localStorage,退出登录时清空vuex及localStorage
  • 【数据库】掌握MySQL事务与锁机制-数据一致性的关键
  • Vue:单文件组件
  • Spring Boot 启动顺序
  • k8s-coredns-CrashLoopBackOff 工作不正常
  • QT多媒体播放器类:QMediaPlayer
  • ollama搭建deepseek调用详细步骤
  • flutter 专题 九十八 Flutter 1.7正式版发布
  • EmbodiedSAM:在线实时3D实例分割,利用视觉基础模型实现高效场景理解
  • I211学习笔记
  • vue3:request.js中请求方法,api封装请求,方法请求
  • 28.Vulmap:Web 漏洞扫描与验证工具
  • Unity | 工具类:单例总结
  • Windows安装MySQL5.7.26教程图解
  • 本周看啥|《歌手》今晚全开麦直播,谁能斩获第一名?
  • 刘国中将出席第78届世界卫生大会并顺访瑞士、访问白俄罗斯
  • 俄媒:俄乌伊斯坦布尔谈判将于北京时间今天17时30分开始
  • 秦洪看盘|缩量回踩,积蓄叩关能量
  • 特朗普中东行:“能源换科技”背后的权力博弈|907编辑部
  • 杞支雅男评《1517》|放眼世界,立足德国