JavaScript 面试题
目录

请解释 JavaScript 中的可选链操作符 (?.) 的作用和用法。

· 约 5 分钟读完 · 第 151 / 507 章

推荐答案

可选链操作符 ?. 允许你访问嵌套对象属性时,如果中间的某个属性为 null 或 undefined,则会短路返回 undefined,而不会抛出错误。这使得处理可能不存在的属性变得更加安全和简洁。

例如:

本题详细解读

可选链操作符的引入背景

在 JavaScript 中,访问嵌套对象的属性时,经常需要进行多次的 && 操作来避免 TypeError: Cannot read property ... of undefined 类型的错误。这种写法冗长且容易出错。 可选链操作符 ?. 的出现就是为了简化这种写法,提高代码的可读性和健壮性。

可选链操作符的用法

?. 操作符可以用于以下几种场景:

  1. 访问对象属性: obj?.prop

    • 如果 obj 为 null 或 undefined,表达式返回 undefined。
    • 否则,返回 obj.prop 的值。
  2. 访问数组元素: arr?.[index]

    • 如果 arr 为 null 或 undefined,表达式返回 undefined。
    • 否则,返回 arr[index] 的值。
  3. 调用函数: func?.(args)

    • 如果 func 为 null 或 undefined,表达式返回 undefined。
    • 否则,调用 func 并返回其结果。
  4. 访问动态属性 obj?.[expression]

    • 如果 obj 为 null 或 undefined,表达式返回 undefined。
    • 否则,返回 obj[expression] 的值。

链式使用

?. 最大的优点在于它可以链式使用,即可以在多个层级上进行可选链操作。例如:obj?.prop1?.prop2?.prop3。如果链中的任何一个属性为 null 或 undefined,整个表达式都会返回 undefined,而不会抛出错误。

示例解释

在推荐答案的示例中:

  • const city2 = user?.profile?.address?.city; 这行代码使用了可选链操作符。如果 user 为 null 或 undefined,则 user?.profile 会返回 undefined,整个表达式也会返回 undefined,不会报错。如果 user 存在,但 user.profile 为 null 或 undefined,则 user?.profile?.address 会返回 undefined,依此类推。
  • 这使得我们能够安全地访问深层嵌套的属性,而无需进行大量的 if 条件判断。

与 && 的区别

可选链操作符 ?. 和 && 都可以用来避免访问 null 或 undefined 属性时的错误,但是它们的行为略有不同:

  • && 会进行短路求值,只有在左侧表达式为真值时才会继续执行右侧表达式。如果左侧表达式为假值(例如 0, '', false, null, undefined),则直接返回左侧表达式的值。
  • ?. 只检查左侧表达式是否为 null 或 undefined,如果是则直接返回 undefined,否则才会继续访问属性。

因此,?. 更专注于检查 null 和 undefined,而 && 则更关注真值和假值。在访问对象属性时,通常使用 ?. 更加清晰和准确。

注意事项

  • 可选链操作符只能用于访问属性,不能用于赋值。
  • 可选链操作符返回的始终是 undefined 或属性值,不会抛出错误。
  • ?. 操作符只能在 ES2020 及以后的版本中使用。在旧版本的 JavaScript 中,需要使用传统的 && 检查或 try-catch 语句来处理 null 或 undefined 的情况。