你怎么看这个JavaScript代码? (var1?var2:var3) [英] How do you read this JavaScript code? (var1 ? var2:var3)
问题描述
我在 JavaScript 代码中看到过这种格式,但找不到编辑后续内容:
感谢所有快速解答!我觉得它就像那样。现在,对于奖励积分:
你能用
(var1?var2)
来做同样的事情
if(var1){
var2
}
?
众所周知作为 三元 (因为它有三个操作数)条件(因为它是if / else / then)运算符。
它被计算为一个值,所以你通常会用它来分配一个值,例如:
var result = condition? value1:value2;
相当于:
var result;
if(condition == true){
result = value1;
} else {
result = value2;
}
例如:
var message =长度是+ len ++(len == 1?foot:feet);
注意?:
是完整的运营商。它不是?
和:
运算符,所以?
by在Javascript中本身毫无意义。
I've seen this format used in JavaScript code, but can't find a good source for the meaning.
Edit for a follow-up:
Thanks for all the quick answers! I figured it was something like that. Now, for bonus points:
can you use (var1 ? var2)
to do the same thing as
if (var1) {
var2
}
?
It's known as a ternary (because it has three operands) conditional (because it's an if/else/then) operator.
It is evaluated to a value, so you would usually use it to assign a value, such as:
var result = condition ? value1 : value2;
Which is equivalent to:
var result;
if (condition == true) {
result = value1;
} else {
result = value2;
}
An example:
var message = "Length is " + len + " " + (len==1 ? "foot" : "feet");
Note ?:
is the full operator. It's not a ?
and :
operator, so ?
by itself is meaningless in Javascript.
这篇关于你怎么看这个JavaScript代码? (var1?var2:var3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!