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

时间:2017-02-22 04:41:02

标签: javascript

我想知道在javascript中编写条件语句时哪些更适合使用

if(false){}

if(undefined){} 

我也知道if(undefined)将被转换为false是javascript

背景

我有一个功能&像这样的对象

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

我正在调用这个函数

someFunc(true);

如果我这样调用someFunc()而不传递参数,那么key2将是未定义的。

后来我想在条件语句中使用这个键

if(obj.key2){

}

如上所述,我知道如果obj.key2未定义,它将被强制为if(false)

4 个答案:

答案 0 :(得分:1)

如果您需要特定检查值类型,则必须使用以下类似的内容。

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

其他使用if(false)或if(undefined)都可以。

答案 1 :(得分:1)

您所询问的内容称为“对象检测”。代码需要以检测对象是否存在的方式构建。如果是这样,那么对该对象进行操作。使代码防弹/无bug的首选方法是:

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

要在JavaScript中使用var关键字正确使用未定义类型(为了避免此SO文章中描述的意外条件翻转行为:Behavior of the typeof keyword),您可能需要在其前面加上“typeof”关键字。然后可以使用三重等于“===”运算符将其输出作为字符串进行比较。像这样:

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

我倾向于使用这些可选括号,但它们不是必需的。这只是一种编码风格,我喜欢阅读:

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

然后你的代码看起来像这样:

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.
   }
};

这只是一个例子,但您不需要对象检测,因为您将obj声明为全局&然后在函数中为其赋值。你明白为什么吗?

最好将var放入函数中,如下所示:

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

将其从全球范围中删除将其范围扩展到功能块本身。

我还建议您了解“let”关键字&它如何取代“var”。

有点棒,看起来像这样:

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
});

答案 2 :(得分:1)

'false'和'undefined'的定义:

如果您提供一个比较false的if语句,那么它会专门寻找布尔值 false。但是,如果变量未定义,则无论如何它都会自动为假。

如果if语句查找未定义,则它专门查找从未定义过的变量或未定义为其值的变量。 if语句if (!variable)将接受false或undefined作为变量的值。

那么底线是什么?

当且仅当if语句如下所示时,它与false或undefined没有区别:

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

但是,如果语句看起来像是在下面,它将只接受其中一个,具体取决于它与之匹配:

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

答案 3 :(得分:0)

我认为,这取决于方案如何检查值。

  • 如果要检查是否存在任何值 您只需要<input type='text' name='username' [value]="search.username" /> <input type='checkbox' name='enableStats' [value]="search.enableStats" />

  • 如果要检查的值不存在,则与先前条件相反,就像class CarouselVariableHight extends StatefulWidget { @override CarouselVariableHightState createState() => CarouselVariableHightState(); } final widgetHeights = <double>[ Random().nextInt(300).toDouble(), Random().nextInt(300).toDouble(), Random().nextInt(300).toDouble(), Random().nextInt(300).toDouble(), ]; class CarouselVariableHightState extends State<CarouselVariableHight> { double height; GlobalKey stackKey = GlobalKey(); bool widgetHasHeigh; @override void initState() { WidgetsBinding.instance.addPostFrameCallback(_afterLayout); super.initState(); } _afterLayout(_) { final RenderBox renderBoxRed = stackKey.currentContext.findRenderObject(); final sizeRed = renderBoxRed.size; setState(() { height = sizeRed.height; }); } final caruselItems = widgetHeights .map((height) => Column(children: [ Container( color: Colors.red, height: Random().nextInt(300).toDouble(), child: Text('Text with random length')) ])) .toList(); _buildStack() { Widget firstElement; if (height == null) { firstElement = Container(); } else { firstElement = Container( height: height, child: PageView( children: caruselItems, ), ); } return IndexedStack( key: stackKey, children: <Widget>[ firstElement, ...caruselItems, ], ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Carousel')), body: ListView( children: <Widget>[ Text('My Carousel'), _buildStack(), Text('end of List'), ], ), ); } }

  • 如果要检查特定类型,则可以使用if(obj.key2)进行类型检查 if(!obj.key2)===

  • 否则,您可以将默认值设置为false。 if(obj.key2 === undefined),ES6也提供了很好的功能,可以将默认值分配给参数。 if(obj['key2'] === undefined)

  • 希望这可以使您清楚。