[英]Can somebody explain this javascript statement to me?
I am working on a project which needs a lot of javascript coding. 我正在一个需要大量JavaScript编码的项目中。 And I'm new to Javascript. 而且我是Java的新手。
Just found a code but can't understand. 刚刚找到一个代码,但是不明白。 Can somebody explain to me? 有人可以向我解释吗? I tried to search for answers but turn out with no result. 我试图寻找答案,但没有结果。
var keyCode = (e.keyCode ? e.keyCode : e.which);
I just wanna know what '?' 我只是想知道什么? and ':' mean in the above code. 和':'在上面的代码中表示。 And is there any alternative way to write it? 还有其他替代的编写方式吗?
Thanks a lot. 非常感谢。
The syntax you see is called a ternary operator . 您看到的语法称为三元运算符 。 It is often used when an if... else...
statement may be unnecessary, or too long. 当if... else...
语句可能不必要或太长时,通常使用它。 You will see it a lot in conditional variable assignments like the one above. 在上面的条件变量分配中,您会看到很多。
Basically, the syntax is like this: 基本上,语法是这样的:
([condition to test] ? [what should we do if true] : [what should we do if false])
. ([condition to test] ? [what should we do if true] : [what should we do if false])
。
It is shorthand for 它是速记
if([condition to test]) {
[what should we do if true];
}
else {
[what should we do if false];
}
In that example, we are trying to assign var keyCode
. 在该示例中,我们尝试分配var keyCode
。 Since some browsers use e.which
to pass in the numeral value of the key pressed, we have to account for both e.keyCode
or e.which
, and assign the appropriate value. 由于某些浏览器使用e.which
来传递按下的键的数字值,因此我们必须考虑e.keyCode
或e.which
并分配适当的值。
Also important to note : e.keyCode
is not necessarily a boolean value. 同样要注意的重要事项 : e.keyCode
不一定是布尔值。 However, in JavaScript, any variable can be interpreted as boolean. 但是,在JavaScript中, 任何变量都可以解释为布尔值。 e.keyCode
has boolean value false
if it's not defined. e.keyCode
布尔值false
如果未定义)。
var keyCode;
if (e.keyCode) {
keyCode = e.keyCode;
} else {
keyCode = e.which;
}
It's a shorthand for if/else. 这是if / else的简写。
var keyCode;
if (e.keyCode) {
keyCode = e.keyCode;
} else {
keyCode = e.which;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.