检查变量是否为空 - Angular 2

时间:2016-04-01 15:54:42

标签: angular

如何在Angular 2中检查变量是否为空?我知道有一些本地方式,如

if (myVar === null) {do stuff}

但我正在寻找像Angular 1这样的东西,比如

if (angular.isEmpty(variable)) { do stuff }

如何使用Angular 2检查变量是否为空?

7 个答案:

答案 0 :(得分:16)

假设我们有一个名为x的变量,如下所示:

var x;

以下声明有效,

x = 10;
x = "a";
x = 0;
x = undefined;
x = null;

1。号:

x = 10;
if(x){
//True
}

以及x = undefinedx = 0(请注意此处)

if(x){
 //False
}

2。字符串x = nullx = undefinedx = ""

if(x){
  //False
}

3布尔x = falsex = undefined

if(x){
  //False
}

通过牢记这一点,我们可以轻松地检查Angular js中的变量是否为空,null,0或未定义。 Angular js doest提供单独的API来检查变量值空白。

答案 1 :(得分:4)

if( myVariable ) 
{ 
    //mayVariable is not : 
    //null 
    //undefined 
    //NaN 
    //empty string ("") 
    //0 
    //false 
}

答案 2 :(得分:3)

您可以在这里玩不同类型并检查输出,

Demo

export class ParentCmp {
  myVar:stirng="micronyks";
  myVal:any;
  myArray:Array[]=[1,2,3];
  myArr:Array[];

    constructor() {
      if(this.myVar){
         console.log('has value')     // answer
      }
      else{
        console.log('no value');
      }

      if(this.myVal){
         console.log('has value') 
      }
      else{
        console.log('no value');      //answer
      }


       if(this.myArray){
          console.log('has value')    //answer
       }
       else{
          console.log('no value');
       }

       if(this.myArr){
             console.log('has value')
       }
       else{
             console.log('no value');  //answer
       }
    } 

}

答案 3 :(得分:1)

你正在寻找那个:

isEmptyObject(obj) {
  return (obj && (Object.keys(obj).length === 0));
}

(找到here

或那:

function isEmpty(obj) {
    for(var key in obj) {
        if(obj.hasOwnProperty(key))
            return false;
    }
    return true;
}

找到here

答案 4 :(得分:1)

user:Array[]=[1,2,3];
if(this.user.length)
{
    console.log("user has contents");
}
else{
    console.log("user is empty");
}

答案 5 :(得分:0)

这取决于您是否知道给定变量类型。如果您希望它是对象,那么您可以检查myVar是否为空对象

 public isEmpty(myVar): boolean {
     return (myVar && (Object.keys(myVar).length === 0));
 }

否则: if(!myVar){} ,应该做的工作

答案 6 :(得分:0)

角度4为空数据,否则

if(this.data == 0)
{
alert("Null data");
}
else
{
//some logic
}