JavaScript中变量前的感叹号是什么意思 [英] What does an exclamation mark before a variable mean in JavaScript

查看:68
本文介绍了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's variable.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 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆