Javascript - 如果语句同时检查表达式和定义声明?这是令人困惑的

Javascript - If statements check both expression and definition declaration? This is confusing

本文关键字:声明 定义 语句 如果 表达式 检查表 检查 Javascript      更新时间:2023-09-26
var boolTrue = true;
var randomObject;
if (boolTrue)
// this will fire
if (randomObject)
// this will fire, because the object is defined
if (!objectNotDefined)
// this will fire, because there is no defined object named 'objectNotDefined'
来自

C++和C#背景,我非常熟悉基本的if(表达式(语法。 但是,我认为同时具有表达式(真/假(并且将对象存在也作为表达式的可读性不是很好。 因为现在如果我看到如下所示的函数,我不知道传入的数据是对象(存在/未定义的检查(还是布尔值。

function(data) {
   if (data)
      // is this checking if the object is true/false or if the object is in existence?
}

事实就是这样吗? 我的意思是,有没有办法轻松阅读这个? 另外,这在JS规范中的任何地方都记录在哪里(好奇(?

在Javascript中,除了false0undefinednullNaN和空字符串之外,一切都是"真实的"(或者更准确地说是"真实的">

(。

为避免混淆,请使用:

 if (data === true) // Is it really true?

if (typeof data === 'undefined') // Is the variable undefined?

您可以单独检查(不存在(存在:

if ( typeof variable == 'undefined' ) {
  // other code
}

但是,您显示的语法通常用作更短的形式,并且在大多数用例中就足够了。

以下值等效于条件语句中的 false:

false
null
undefined
The empty string ”
The number 0
The number NaN

它检查它是否真实

在 JavaScript 中,除了 false0""undefinednullNaN之外,一切都是真实的。

因此,true将传递,以及任何对象(也是空对象/数组/等(。

请注意,如果您的意思是"已声明但未定义",则您的第三条注释为真 - 从未声明的变量会在访问时引发ReferenceError。一个声明的,未定义的变量(var something;(是undefined的(所以,不是真实的(,所以如果你否定它,它确实会通过条件。