[javascript] 判斷變數 null、undefined及空值

  1. 判斷變數為 null 或 undefined 或 “”
    if(!str)
    {
          var str;
          console.log("str is null or undefined or '' ");
    }
    
  2. 判斷變數是否存在
    if(typeof str === "undefined")
          console.log("str is not exist");
    

    PS. === 可以辨別型態, == 則會轉型單純比值

參考資料:

http://www.ruanyifeng.com/blog/2011/05/how_to_judge_the_existence_of_a_global_object_in_javascript.html

Leave a Reply

Your email address will not be published. Required fields are marked *