如何在 JavaScript 中编写内联 IF 语句?
问题描述:
如何在 JavaScript 中使用内联 if
语句?是否也有内联 else
语句?
How can I use an inline if
statement in JavaScript? Is there an inline else
statement too?
像这样:
var a = 2;
var b = 3;
if(a < b) {
// do something
}
答
您不一定需要 jQuery.仅 JavaScript 就可以做到这一点.
You don't necessarily need jQuery. JavaScript alone will do this.
var a = 2;
var b = 3;
var c = ((a < b) ? 'minor' : 'major');
如果值为 true
,c
变量将为 minor
,如果值为 major
代码>假代码>.
The c
variable will be minor
if the value is true
, and major
if the value is false
.
这称为条件(三元)运算符.
This is known as a Conditional (ternary) Operator.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator