JavaScript替代方案 [英] JavaScript if alternative

查看:282
本文介绍了JavaScript替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码代表什么?我知道它是某种如果替代语法......

What does this bit of code represent? I know it's some kind of if alternative syntax...

pattern.Gotoccurance.score != null ? pattern.Gotoccurance.score : '0'

更新:

这种编码有什么需要?这是效率更高还是效率相同的缩短版本?

What's the need for this sort of coding? Is this more efficient or just a shortened version with the same efficiency?

推荐答案

这是条件运算符,它相当于这样:

It is the conditional operator, it is equivalent to something like this:

if (pattern.Gotoccurance.score != null) {
  pattern.Gotoccurance.score;
} else {
  '0';
}

但我认为你发布的代码中缺少一个赋值语句,比如这个:

But I think that an assignment statement is missing in the code you posted, like this:

var score = pattern.Gotoccurance.score !=null ? pattern.Gotoccurance.score : '0';

如果<分配得分变量code> pattern.Gotoccurance.score 不为空:

The score variable will be assigned if pattern.Gotoccurance.score is not null:

var score;
if (pattern.Gotoccurance.score != null) {
  score = pattern.Gotoccurance.score;
} else {
  score = '0';
}

在JavaScript中执行此类默认值分配的常见模式是使用逻辑OR运算符( || ):

A common pattern to do this kind of 'default value' assignments in JavaScript is to use the logical OR operator (||) :

var score = pattern.Gotoccurance.score ||  '0';

pattern.Gotoccurance.score 的值仅当该值不是 falsy 时才会被分配到得分变量(假值为 false null undefined 0 ,零 - 长度字符串或 NaN )。

The value of pattern.Gotoccurance.score will be assigned to the score variable only if that value is not falsy (falsy values are false, null, undefined, 0, zero-length string or NaN).

否则,如果它是假的'0'将被分配。

Otherwise, if it's falsy '0' will be assigned.

更新:性能相当,你应该专注于可读性,我尝试使用表达式上的三元运算符非常简单,你也可以改进格式,将它分成两行以使其更具可读性:

Update: The performance will be equivalent, you should focus on readability, I try to use the ternary operator on expressions that are very simple, and you can also improve the formatting, splitting it up in two lines to make it more readable:

var status = (age >= 18) ? "adult"
                         : "minor";

相关问题:

  • To Ternary or Not To Ternary?

这篇关于JavaScript替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆