Skip to content

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

Published: at 03:20 AM (1 min read)
  1. 判斷變數為 null 或 undefined 或 ""

    [javascript] if(!str) { var str; console.log(“str is null or undefined or ” ”); } [/javascript]

  2. 判斷變數是否存在

    [javascript] if(typeof str === “undefined”) console.log(“str is not exist”); [/javascript]

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

參考資料:

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