JavaScript中变量前的感叹号是什么意思 [英] What does an exclamation mark before a variable mean in JavaScript
问题描述
我正在尝试通过浏览应用程序中的一些代码来学习 JavaScript,但我一直在 if 条件中看到 !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?
推荐答案
!
是 逻辑非运算符.
!expression
读作:
- 取
expression
并计算它.在你的情况下是variable.onsubmit
- 大小写该评估的结果并将其转换为布尔值.在您的情况下,由于
onsubmit
可能是一个函数,这意味着 - 如果该函数为 null 或未定义 - 返回 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).
简单地说 - !variable
意味着取 variable
的真值并取反.
Simply put - !variable
means take the truth value of variable
and negate it.
因此,if (!variable) {
将进入 if
子句 if variable is false
(或强制为 false)
Thus, if (!variable) {
will enter the if
clause if variable is false
(or coerces to false)
if (!variable.onsubmit || (variable.onsubmit() != false)) {
Means - 检查 variable.onsubmit
是否已定义且为真(因此为真),然后检查调用 onsubmit
是否返回强制为真的结果.在简短的一行中,它检查是否没有 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屋!