发布于 2026-01-06 0 阅读
0

JavaScript 中的逻辑或运算符 (||) 与空合并运算符 (??)

JavaScript中的逻辑或运算符 (||) 与空合并运算符 (??)

随着 NodeJS 14 版本的发布,空值合并运算符 (??) 现在已在 NodeJS 中得到支持。本文将探讨此运算符的用途以及它与逻辑 OR 运算符的区别。

逻辑或 (||)

const paginate = (options = {}) => {
  return [1, 2, 3, 4, 5].splice(0, options.limit || 3);
}

paginate(1); // expected: [1], output: [1]
paginate(); // expected: [1, 2, 3], output: [1, 2, 3]
paginate(0); // expected: [], output: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

逻辑或运算符的工作原理是:如果左侧的值强制为假,则返回右侧的值。这不仅包括undefined“与” null,还包括“0与” ''

在我们的许多使用场景中,例如上面的例子,这样做会导致意想不到的结果,最终我们不得不使用typeof运算符。

无效合并算子(??)

null这样就解决了我们的问题。该运算符仅当左侧值为真或假时才返回右侧值undefined

const paginate = (options = {}) => {
  return [1, 2, 3, 4, 5].splice(0, options.limit ?? 3);
}

paginate(1); // expected: [1], output: [1]
paginate(); // expected: [1, 2, 3], output: [1, 2, 3]
paginate(0); // expected: [], output: []
Enter fullscreen mode Exit fullscreen mode

在评论区分享你编写的简短 JavaScript 代码吧。

文章来源:https://dev.to/hereisnaman/tical-or-vs-nullish-coalescing-operator-in-javascript-3851