简体   繁体   English

条件语句中的if(false)vs if(undefined)

[英]if(false) vs if(undefined) in conditional statement

I will like to know which will be more appropriate to use while writing a conditional statement in javascript 我想知道在用javascript编写条件语句时更适合使用哪种方法

if(false){}

or 要么

if(undefined){} 

Also I know if(undefined) will be converted to false is javascript 我也知道if(undefined)将被转换为false是javascript

Background 背景

I have a function & an object like this 我有这样的功能和对象

var obj ={}
var someFunc = function(a){
     obj = {
         key1:true,
         key2:a, // i will like to have it as a?true:false
         key3: !a
    }

I am calling the function like this 我正在这样调用函数

someFunc(true);

if I call like this someFunc() , without passing the argument , then key2 will be undefined. 如果我这样调用someFunc() ,而不传递参数,则key2将是未定义的。

later I want to use this key in conditional statement 稍后我想在条件语句中使用此键

if(obj.key2){

}

As mentioned I know if obj.key2 is undefined, it will be coerced as if(false) . 如前所述,我知道obj.key2是否未定义,它将被强制为if(false)

if you need to check specifically value type then you have to use following like this. 如果您需要检查具体的值类型,则必须使用以下代码。

if(value === false){} 
or
if(value === undefined){}

other that using if(false) or if(undefined) are ok. 其他使用if(false)或if(undefined)都可以。

What you're asking about is known as "Object Detection". 您要问的是“对象检测”。 The code needs to be built in a way to detect if the object exists & if so, then operate on that object. 需要以某种方式构建代码,以检测对象是否存在,如果存在,然后对该对象进行操作。 The preferred way of making your code bullet-proof / bug free is to do this: 使代码防弹/防bug的首选方法是:

if (obj && obj.key2){ // If object and object property both exist...
  // Do something here...
}

To properly use the undefined type in JavaScript with the var keyword (in order to avoid the unexpected conditional flipping behavior described at this SO article: Behavior of the typeof keyword ), you may want to prefix it with the "typeof" keyword. 要在var关键字中正确使用JavaScript中的未定义类型(为避免发生在本SO文章中描述的意外的条件翻转行为: typeof关键字的行为 ),您可能希望在其前面加上“ typeof”关键字。 Then its output can be compared as a string, using the the triple equal "===" operator. 然后,可以使用三元等于“ ===”运算符将其输出作为字符串进行比较。 Like so: 像这样:

if (typeof value === 'undefined'){ 
  // Do something...
}

I tend to use these optional parenthesis, but they aren't required. 我倾向于使用这些可选的括号,但不是必需的。 It's just a coding style, which I like to read: 这只是一种编码风格,我喜欢阅读:

if (typeof(value) === 'undefined'){ 
  // Do something...
}

Then your code would look like this: 然后您的代码将如下所示:

var obj = {};
var someFunc = function(a){
   obj = {
      "key1": true,
      "key2": a,
      "key3": !a
   };

   // True > False Example:
   if (obj && obj.key2) { // true
      // Do something true...
   } else { // false
      // Do something else...
   }

   // False > True Example, using a "not condition" AKA "!" AKA an exclamation point:
   if (obj && !obj.key3) { // false
      // Here you're checking for the object, but the false value for the key3 property.
   } else if (obj && obj.key3) { // true
      // Here you'd need the object detection again, as you'd be checking for the key3 property on that object.
   }
};

That's just an example, but you won't need the object detection, because you are declaring obj as a global & then assigning values to it in your function. 那只是一个例子,但是您不需要对象检测,因为您将obj声明为全局obj ,然后在函数中为其分配值。 Do you see why? 你明白为什么吗?

It's also better to put the var into the function, like so: 最好将var放入函数中,如下所示:

var obj = {
   "key1": true,
   "key2": a,
   "key3": !a
};

That removes it from the global scope & scopes it into the function block itself. 这会将其从全局范围中删除,并将其范围扩展到功能块本身中。

I'd also recommend learning about the " let " keyword & how it can replace "var". 我还建议您学习“ let ”关键字及其如何替换“ var”。

Something awesome, would look like this: 很棒的东西看起来像这样:

let someFunc = function(json) {
   // Another object detection example:
   if (json) {

      // Since key1 is always true, we don't need the if/else for it.
      // Just add any key1 code here, without the if(...) statement.

      // Switches are faster than if/else-if/else statements.
      switch(json.key2) {
         case true:
            // Do something true with key2...
            break;
         case false:
            // Do something else with key2...
            break;
      }

      switch(json.key3) {
         case true:
            // Do something true with key3...
            break;
         case false:
            // Do something else with key3...
            break;
      }
   }
};

// Usage:
someFunc({
  "key1": true,
  "key2": a,
  "key3": !a
});

Definitions of the 'false' and 'undefined': “ false”和“ undefined”的定义:

If you give an if statement that compares false, then it is specifically looking for the boolean false. 如果给出的if语句比较false,则专门查找布尔值 false。 But, if a variable is undefined, it is automatically false anyway. 但是,如果未定义变量,则无论如何它都会自动为false。

If an if statement looks for undefined, it is specifically looking for a variable that has never been defined or was assigned undefined as its value . 如果if语句查找未定义,则专门查找从未定义或未分配为其值的变量 An if statement if (!variable) will accept both false or undefined as the value of variable. if语句if (!variable)将接受false或undefined作为变量的值。

So what's the bottom line? 那么底线是什么?

It makes no difference from false or undefined if and only if the if statement looks like this: 当且仅当if语句如下所示时,它与false或undefined没有区别:

if (variable) {
// variable can be undefined or false
}

But, if the statement looks like it is below, it will only accept one of the two, depending on which it was matched with: 但是,如果该语句看起来像下面的语句,则它将仅接受这两个语句之一,具体取决于与之匹配的语句:

if (variable == false) {
// Now it strictly must be "false". Undefined is not accepted
}

It's depend on scenario that how do you check the value, in my opinion. 我认为,这取决于方案如何检查值。

  • If you want to check any value exist You just need if(obj.key2) 如果要检查是否存在任何值, if(obj.key2)需要if(obj.key2)

  • If you want to check value does not exist, opposite of previous condition, just like if(!obj.key2) 如果要检查的值不存在,则与以前的条件相反,就像if(!obj.key2)

  • If you want to check specific type, you would have used type check with === either if(obj.key2 === undefined) or if(obj['key2'] === undefined) 如果要检查特定类型,则可以将类型检查与===使用, if(obj.key2 === undefined)if(obj['key2'] === undefined)

  • Else you can set default value as false. 否则,您可以将默认值设置为false。 key2: a || false key2: a || false , Also ES6 has given nice feature for assigning default value into parameter. key2: a || false ,ES6也提供了很好的功能,可以将默认值分配给参数。 function(a = false){ }

  • Hope this will make your clear. 希望这能使您明白。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM