变量前面的感叹号在JavaScript中意味着什么? [英] What does an exclamation mark before a variable mean in JavaScript
问题描述
我正在尝试通过浏览应用程序中的一些代码来学习JavaScript,并且如果有条件,我会一直看到!variable
。例如:
I'm trying to learn JavaScript by going through some code in an application and I keep seeing !variable
in if conditions. For example:
if (!variable.onsubmit || (variable.onsubmit() != false)) {
这是什么?如果变量是空的某种测试?
What is it? Some kind of test if the variable is empty?
推荐答案
!
是JavaScript中的逻辑非运算符。
!
is the logical not operator in JavaScript.
!表达式
读作:
- 获取
表达式
并对其进行评估。在您的情况下,variable.onsubmit
- 判断该评估的结果并将其转换为布尔值。在你的情况下,因为
onsubmit
可能是一个函数,这意味着 - 如果函数为null或未定义 - 返回false,否则返回true。 - 如果评估结果为true,则返回false。否则返回true。
- Take
expression
and evaluate it. In your case that'svariable.onsubmit
- Case the result of that evaluation and convert it to a boolean. In your case since
onsubmit
is likely a function, it means - if the function is null or undefined - return false, otherwise return true. - If that evaluation is true, return false. Otherwise return true.
在你的情况下!variable.onsubmit
表示如果没有定义函数则返回true(因此是假的),否则返回false(因为定义了函数)。
In your case !variable.onsubmit
means return true if there isn't a function defined (and thus is falsy), otherwise return false (since there is a function defined).
简单地说 - !变量
表示采用变量的真值
并否定它。
Simply put - !variable
means take the truth value of variable
and negate it.
因此, if(!variable){
将进入 if
子句如果变量是 false
(或强制为假)
Thus, if (!variable) {
will enter the if
clause if variable is false
(or coerces to false)
if (!variable.onsubmit || (variable.onsubmit() != false)) {
意味着 - 检查 variable.onsubmit
是否已定义且真实(因此为真),那么检查调用 onsubmit
是否返回强制为true的结果。在一个短行中它检查是否没有 onsubmit
或它返回true。
Means - check if variable.onsubmit
is defined and truthy (thus true), then it checks if calling onsubmit
returns a result that coerces to true. In a short line it checks if there is no onsubmit
or it returns true.
- MDN在这里有一个运营商列表。
- 语言规范指定了这样的运算符,虽然它是官方规范,但确实包含一些可能难以理解的术语。
- MDN has a list of operators here.
- The language specification specifies such operators, though being the official specification it does contain some jargon which might be hard to understand.
这篇关于变量前面的感叹号在JavaScript中意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!