处理 JavaScript 中的备选值

19 阅读1分钟

在实际前端开发中,我们经常需要处理可能为 null、undefined 或特定无效值的情况。JavaScript 的空值合并运算符(??)提供了基础解决方案,但面对更复杂的需求时,我们需要更强大的工具。本文介绍一个优雅的备选值处理函数——getValueWithFallback。

函数功能解析

getValueWithFallback 函数接收三个参数:

  • value: 需要检测的值
  • fallback: 备选返回值
  • excludeValues: 可选参数,指定需要排除的值数组

函数逻辑:

  1. 将排除值数组转换为 Set 以提高查询效率
  2. 如果当前值在排除列表中,返回备选值
  3. 否则,如果当前值为 null 或 undefined,返回备选值
  4. 其他情况返回原值

javascript

function getValueWithFallback(value, fallback, excludeValues = []) {
    const exclusionSet = new Set(excludeValues);
    return exclusionSet.has(value) ? fallback : (value ?? fallback);
}

console.log(getValueWithFallback(undefined, '-'));//-
console.log(getValueWithFallback(null, '-'));//-
console.log(getValueWithFallback('', '-'));//''
console.log(getValueWithFallback(0, '-'));//0
console.log(getValueWithFallback(false, '-'));//false
console.log(getValueWithFallback(NaN, '-'));//NaN


console.log(getValueWithFallback('', '-', ['']));//-
console.log(getValueWithFallback(0, '-', [0]));//-
console.log(getValueWithFallback(false, '-', [false]));//-
console.log(getValueWithFallback(NaN, '-', [NaN]));//-