JavaScript'if'替代 [英] JavaScript 'if' alternative

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

问题描述

这段代码代表什么?我知道这是一种if替代语法...

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, and 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';

如果pattern.Gotoccurance.score不为null,则将分配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,nullundefined,零长度字符串或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.

性能将是等同的,并且您应该关注可读性.我尝试在非常简单的表达式上使用三元运算符,并且您还可以改进格式,将其分成两行以提高可读性:

The performance will be equivalent, and 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";

相关问题:

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

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