Gan*_*row 9 javascript ternary-operator conditional-operator
这段代码代表什么?我知道这是一种if替代语法......
pattern.Gotoccurance.score != null ? pattern.Gotoccurance.score : '0'
Run Code Online (Sandbox Code Playgroud)
更新:
这种编码有什么需要?这是效率更高还是只是一个效率相同的缩短版本?
CMS*_*CMS 35
它是条件运算符,它相当于这样的东西:
if (pattern.Gotoccurance.score != null) {
pattern.Gotoccurance.score;
} else {
'0';
}
Run Code Online (Sandbox Code Playgroud)
但我认为你发布的代码中缺少一个赋值语句,如下所示:
var score = pattern.Gotoccurance.score !=null ? pattern.Gotoccurance.score : '0';
Run Code Online (Sandbox Code Playgroud)
该score如果变量将被分配pattern.Gotoccurance.score不为空:
var score;
if (pattern.Gotoccurance.score != null) {
score = pattern.Gotoccurance.score;
} else {
score = '0';
}
Run Code Online (Sandbox Code Playgroud)
在JavaScript中执行此类"默认值"赋值的常见模式是使用逻辑OR运算符(||):
var score = pattern.Gotoccurance.score || '0';
Run Code Online (Sandbox Code Playgroud)
的值pattern.Gotoccurance.score将被分配给该score变量仅当该值不在falsy(falsy值是false,null,undefined,0,零长度的字符串或NaN).
否则,如果它'0'被分配了.
更新:性能将是等效的,您应该专注于可读性,我尝试在非常简单的表达式上使用三元运算符,并且您还可以改进格式,将其分成两行以使其更具可读性:
var status = (age >= 18) ? "adult"
: "minor";
Run Code Online (Sandbox Code Playgroud)
相关问题:
这是一个三元运算符,是if语句的一种缺省方式.
如果重写,它将如下所示:
if (pattern.Gotoccurance.score != null) {
return pattern.Gotoccurance.score;
} else {
return '0';
}
Run Code Online (Sandbox Code Playgroud)