简体   繁体   English

精简JavaScript IF Else

[英]Short Hand JavaScript IF Else

我有JavaScript的简写版本if else函数,并且我想知道如果其他情况正常,它将如何显示:

var criteriaField = criteria.hasOwnProperty('searchTerm') ? 'name': 'price';

It would look like this: 它看起来像这样:

var criteriaField;
if (criteria.hasOwnProperty('searchTerm')) {
  criteriaField = 'name';
} else {
  criteriaField = 'price';
}

You should read more about the ternary operator ( ? ) here . 您应该在此处详细了解三元运算符( ? )。

if (criteria.hasOwnProperty('searchTerm')) var criteriaField = 'name';
else var criteriaField = 'price';

The term before the ? 前一词? operator is the condition, followed by the value if the condition evaluates to true, and then to false. 运算符是条件,如果条件的结果为true,则后跟值,然后为false。 SO, as an if-else statement, it could be written as: 因此,作为if-else语句,它可以写为:

var criteriaField;
if (criteria.hasOwnProperty('searchTerm')) {
    criteriaField = 'name';
} else{
    criteriaField = 'price';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM