三元运算符作为简短的条件语句

发布于 2025-01-08 05:34:39 字数 265 浏览 0 评论 0原文

在 Javascript 中使用三元运算符代替较长的条件语句有什么问题吗,例如使用:

(variable == "dog") ? dog_stuff() : false;

而不是

if ( variable == "dog" ) 
{
    dog_stuff();
}

这听起来像是一个愚蠢的问题,但我只是发现它非常快速且易于阅读,我只是不想成为如果存在可能的缺点,请使用它?

Is there anything wrong with using ternary operators in place of longer conditional statements in Javascript, for instance using:

(variable == "dog") ? dog_stuff() : false;

Rather than

if ( variable == "dog" ) 
{
    dog_stuff();
}

This may sound like a stupid question but I just find it's pretty quick and easy to read, I just don't want to be using it if there's a possible drawback?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

℉絮湮 2025-01-15 05:34:39

也可以这样写

(variable == 'dog') && dog_stuff();

如果没有 else 语句,

。 backbone.js 中的几行:

  options || (options = {});
  models = _.isArray(models) ? models.slice() : [models];
  model = this.getByCid(models[i]) || this.get(models[i]);

如果非常有必要,您可以对多个语句进行分组:

(1==1) && (a=2,b=3)
alert(a); // 2
alert(b); // 3

You could also write

(variable == 'dog') && dog_stuff();

if you don't have an else statement.

A few lines from backbone.js:

  options || (options = {});
  models = _.isArray(models) ? models.slice() : [models];
  model = this.getByCid(models[i]) || this.get(models[i]);

You can group multiple statements, if it's very necessary:

(1==1) && (a=2,b=3)
alert(a); // 2
alert(b); // 3
流星番茄 2025-01-15 05:34:39

这是错误的,因为您告诉代码执行 false。想象一下下面的代码:

if ( variable == "dog" ) 
{
    dog_stuff();
} else {
    false;
}

在我看来,4 行条件函数调用完全没问题。您可以将其简写为:

if (variable == "dog") dog_stuff();

唯一的问题是,如果您将其注释掉,或者添加 1 个以上的函数,那么事情看起来是正确的,但无法正确执行:

if (variable == "dog") dog_walk(); dog_bark(); // dog_bark executes always!
if (variable == "dog") // dog_walk();
earn_cash(); // suddenly earn_cash() is dog-dependent.

It's wrong because you're telling your code to execute false. Imagine the following code:

if ( variable == "dog" ) 
{
    dog_stuff();
} else {
    false;
}

IMO the 4 line conditional function call is perfectly fine. You can shorthand it to:

if (variable == "dog") dog_stuff();

The only problem with this is if you comment it out, or add 1 more function then things look correct, but don't execute correctly:

if (variable == "dog") dog_walk(); dog_bark(); // dog_bark executes always!
if (variable == "dog") // dog_walk();
earn_cash(); // suddenly earn_cash() is dog-dependent.
伪装你 2025-01-15 05:34:39

只要您和其他可能需要阅读代码的人能够轻松理解该格式,就可以了。

As long as the format is easily understood by you and anyone else that may need to read the code, it's fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文