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

三元运算符:更佳替代方案

三元运算符:更佳替代方案

三元运算符是一种简洁的赋值方式,无需编写冗长的代码if/else
例如:

// This...
let value;
if (test) value = 1;
else value = 2;

// can be written as this:
const value = test ? 1 : 2;
Enter fullscreen mode Exit fullscreen mode

然而,三元运算符很容易被误用,在某些情况下,更简单的运算符可能才是更好的选择。因此,这里列举一些常见错误的替代方案。

静态真/假赋值:

const value = test ? true : false;
// can be replaced by boolean casting:
const value = !!test;
// or even
const value = Boolean(test); // I prefer the shorter alternative
Enter fullscreen mode Exit fullscreen mode

可为空赋值(假值情况)

const value = test ? test : null;
// can be written like this
const value = test || null;
Enter fullscreen mode Exit fullscreen mode

注意:只要testis为假值,上面的代码就会返回 null 。

可空赋值(接近空的情况)

const value = test !== null || test !== undefined ? test : null;
// can be written like this:
const value = test ?? null;
Enter fullscreen mode Exit fullscreen mode

参见:空合并运算符(??)

顺便一提...

const test = a === null || a === undefined;
// can be simplified as:
const test = a == null;
Enter fullscreen mode Exit fullscreen mode

检查是否未定义

我见过好几次了,真的。

const value = obj ? obj.a : undefined;
// which can simply be:
const value = obj && obj.a;
// or in more recent implementations:
const value = obj?.a;
Enter fullscreen mode Exit fullscreen mode

参见:可选链式调用(?.)[猫王运算符]

注意浏览器兼容性。如果要安全地使用可选链,最好使用配置为将代码转译为 ES5 的 TypeScript,并将模块配置为 esnext,以便使用最新的 ECMAScript 特性。

三元运算符(但实际上并非三元运算符)

这是我最喜欢的一个例子,也是一个无心之失。有些人会被三元运算符的简洁性冲昏头脑,误以为它只是一个“更短”的if/else语句。

let value;
test ? value = 8 : null;
// when they meant 
if (test) value = 8;
Enter fullscreen mode Exit fullscreen mode

单行if语句简洁明了,足以满足此目的,但我们知道它test ? value = 8无法正常工作。三元运算符需要else返回值。如果不需要返回值,请使用单行语句if

另一种变体

在 React 中,有时当我们想在特定条件为真时渲染组件时,我们可能会看到类似这样的情况。

{ myCondition ? <MyComponent /> : null }
// when they meant 
{ myCondition && <MyComponent /> }
Enter fullscreen mode Exit fullscreen mode

对于下面的示例,我只会使用三元运算符来选择渲染哪个组件。

总结一下……

简而言之,如果你的三元运算符没有像下面这样的结构,你应该引起注意,并检查是否真的有其他更简单的替代方案。

const value = test ? otherValue : anotherValue;
Enter fullscreen mode Exit fullscreen mode

你还能想到其他三元运算符使用不当的例子吗?请在下方评论区留言告诉我。

文章来源:https://dev.to/saulodias/ternary-operator-better-alternatives-2ind