这段代码代表什么?我知道它是某种如果替代语法......
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还是Not to Ternary?
- To Ternary or Not To Ternary?
更多推荐
JavaScript替代方案
发布评论