JavaScript null check

前端 未结 8 1001
小鲜肉
小鲜肉 2020-12-04 06:20

I\'ve come across the following code:

function test(data) {
    if (data != null && data !== undefined) {
        // some code here
    }
}
         


        
8条回答
  •  爱一瞬间的悲伤
    2020-12-04 06:39

    typeof foo === "undefined" is different from foo === undefined, never confuse them. typeof foo === "undefined" is what you really need. Also, use !== in place of !=

    So the statement can be written as

    function (data) {
      if (typeof data !== "undefined" && data !== null) {
        // some code here
      }
    }
    

    Edit:

    You can not use foo === undefined for undeclared variables.

    var t1;
    
    if(typeof t1 === "undefined")
    {
      alert("cp1");
    }
    
    if(t1 === undefined)
    {
      alert("cp2");
    }
    
    if(typeof t2 === "undefined")
    {
      alert("cp3");
    }
    
    if(t2 === undefined) // fails as t2 is never declared
    {
      alert("cp4");
    }
    

提交回复
热议问题