Javascript !undefined 为真?

Javascript !undefined gives true?

当我尝试警告具有 undefined 值的变量的否定时,我得到的输出为 true?

alert(undefined);
alert(!undefined);

第一个警报给出 undefined,第二个警报给出 true。 这是预期的行为吗?如果是,那为什么?我是否在 Javascript 中遗漏了一些关于 undefined 的 concept/theory?

是的,没错。 undefined 是一个 falsy 值。

https://developer.mozilla.org/ru/docs/Glossary/Falsy

https://developer.mozilla.org/ru/docs/Glossary/Truthy

是的,这是预期的行为。

以下值的否定在 javaScript 中为真:

  • 未定义
  • 0(数字零)
  • ""(空字符串)

例如:!undefined = true

注意: 当你 == 将它与 false 进行比较时,以下检查 return 为真,但它们的否定将 return 为假。

  • " "(仅限 space)。
  • [ ](空数组),

例如:[ ] == false 给出 true,但是 ![ ] 给出 false

Is this the expected behavior.

是的。

If so then why ?Am I missing some concept/theory about undefined in Javascript?

JavaScript 具有值的隐式转换 的概念(又名强制值)。当您使用 negation ("NOT") operator (!), the thing you're negating has to be a boolean, so it converts its argument to boolean if it's not boolean already. The rules for doing that are defined by the specification 时:基本上,如果值为 undefinednull""00nNaN(在浏览器上也是 document.all),它强制转换为 false;否则,它强制为 true.

所以 !undefinedtrue 因为 undefined 隐式转换为 false,然后 ! 否定它。

这些值(和 false)统称为 falsy values. Anything else¹ is called a truthy value。这个概念发挥了很多作用,不仅在 ! 中,而且在 if 中的测试和循环以及对某些内置函数(如 Array.prototype.filter,等等


¹ document.all 在浏览器上是虚假的,即使它是一个对象,并且所有(其他)对象都是真实的。如果您对……有趣的……历史感兴趣,请查看我最近出版的书 JavaScript:新玩具 的第 17 章。基本上,这是为了避免网站不必要地使用非标准、过时的功能。