直接用等號去判斷一個變數是否為 undefined,往往會得到不如预期的結果。以下示範常見的錯誤寫法與正確做法。
容易出錯的寫法:
if (reValue == undefined){
alert("undefined");
}
這樣常常判斷不出來,查了資料後才發現必須使用 typeof。正確寫法如下:
if (typeof(reValue) == "undefined") {
alert("undefined");
}
這是因為 typeof 回傳的是字串,共有六種可能:"number"、"string"、"boolean"、"object"、"function"、"undefined"。使用 typeof 判斷,才能準確辨識變數是否為 undefined。