在 JavaScript 中,有几种常见的方式可以为变量或函数参数设置默认值:

1. 逻辑或操作符 || (传统方式)

let name = userInput || '默认姓名';
  • 当 userInput 为 falsy 值(如 nullundefined''0falseNaN)时使用默认值

  • 缺点:会覆盖所有 falsy 值,有时可能不符合预期

2. 空值合并操作符 ?? (ES2020)

let name = userInput ?? '默认姓名';
  • 只在 userInput 为 null 或 undefined 时使用默认值

  • 不会覆盖其他 falsy 值(如 0false''

3. 函数参数默认值 (ES6)

function greet(name = '匿名用户', age = 18) {
  console.log(`你好,${name},你今年${age}岁`);
}

4. 对象属性默认值

使用解构赋值设置默认值

const { username = '访客', level = 1 } = userObject;

使用 Object.assign()

const defaults = { color: 'red', size: 'medium' };
const settings = Object.assign({}, defaults, userSettings);

5. 数组解构默认值

const [first = 0, second = 0] = numberArray;

6. 使用 ??= 逻辑空值赋值 (ES2021)

let config = {};
config.timeout ??= 5000; // 只在 timeout 为 null/undefined 时赋值

实际应用示例

// 用户设置合并默认设置
function getUserSettings(userSettings) {
  const defaults = {
    theme: 'light',
    notifications: true,
    itemsPerPage: 10
  };
  
  return { ...defaults, ...userSettings };
}

// API 响应处理
async function fetchData() {
  try {
    const response = await fetch('/api/data') ?? { data: [] };
    const { data = [] } = await response.json();
    return data;
  } catch {
    return [];
  }
}

注意事项

  1. || 和 ?? 的区别:

    • || 对任何 falsy 值都会触发默认值

    • ?? 只在 null 或 undefined 时触发

  2. 函数参数默认值只在参数为 undefined 时生效,null 不会触发

  3. 现代 JavaScript 开发推荐使用 ?? 而不是 || 来设置默认值,因为它更精确