JavaScript的“if”替代方案

11

这段代码代表什么意思?我知道它是一种某种类型的if语句的替代语法...

pattern.Gotoccurance.score != null ? pattern.Gotoccurance.score : '0'
这种编码方式的必要性是什么?它是更高效的还是只是一个缩短了但具有相同效率的版本?
5个回答

38

这是一个三目运算符,相当于下面的语句:

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

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

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

如果 pattern.Gotoccurance.score 不为 null,则变量 score 将被分配:

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

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

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

只有当pattern.Gotoccurance.score的值不为假值(假值包括falsenullundefined0,长度为零的字符串或NaN)时,score变量才会被赋值为该值。

否则,如果它是假值,则会分配'0'

性能将是等效的,应专注于可读性。我尝试在非常简单的表达式上使用三元运算符,并且您还可以改进格式,将其分成两行以使其更易读:

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

相关问题:


哦,好的,为什么需要这种编码方式,是更高效还是只是缩短了代码但效率相同? - Gandalf StormCrow
解释时间会影响性能吗? - barkmadley
这是一种有所作为的回答。当涉及到JavaScript和三元运算符时,不再有疑虑。做得好CMS。 - Leniel Maccaferri

5
这是一个三元运算符,它是if语句的一种简写方式。
如果重新编写,它会变成这样:
if (pattern.Gotoccurance.score != null) {
   return pattern.Gotoccurance.score;
} else {
   return '0';
}

1
"ternary" 的意思是“具有三个参数的函数”。? .. : ... 是条件运算符。 - Jacob Krall

2
它被称为三元运算符。

3
这是一个三目运算符。它恰好是该语言中唯一的三目运算符,但可能存在其他理论上的三目运算符。 - Samantha Branham

0

这是三元运算符/条件运算符。

在数学中,三元运算 是一个具有 n = 3 的 n 元运算。对于集合 A 上的三元运算将任意给定的三个 A 中的元素组合起来形成 A 的单个元素。

它是 if..else 的简写形式。

例如,想要找出一个数字是否为偶数。

使用 if..else 方法

function CheckEvenOdd()
{
    var number = 2;
    if(number % 2 == 0)
        alert("even");
    else
        alert("odd");
}

使用三元运算符

function CheckEvenOdd()
{
    var number = 2;
    alert((number %2 == 0) ? "even" : "odd");
}

使用 switch

另一种选择是 switch:

function CheckEvenOdd()
{
    var number = 2;
    switch(number % 2)
    {
        case 0:
            alert("even");
            break;
        default:
            alert("odd");
            break;
    }
}

现在,如果您需要执行类似于所描述的简单if..else条件,则可以使用三元运算符。

但是,如果条件检查变得复杂,请使用if..elseswitch,因为在三元运算符中可读性会降低。

例如,使用三元运算符很容易获得两个数字的最小值或最大值,但是在三个或更多数字中找到最大值和第二大值变得笨拙,甚至不建议使用。最好使用if..else代替。


0

关于此类编码的需求:

有时可以使用三元运算符来减少复杂性:

例如,我有一个网页需要验证至少填写了三个特定文本字段中的两个。 if / else逻辑看起来很丑陋,但是使用三元运算符可以将其转换为单行以确定填写了多少个字段:

var numberFilledInFields = ( (firstName.length > 0 ? 1 : 0) +
                     (lastName.length > 0 ? 1 : 0) +
                     (zipCode.length > 0 ? 1 : 0) );

if (numberFilledInFields < 2)
{
    validation = false;
    return;
}

这个解决方案看起来比一些替代方案更优雅、易读。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接