用來判斷變數的資料型別:
var message = "some string"; alert(typeof message); // "string" alert(typeof(message)); // "string" alert(typeof 100); // "number"
可能的回傳值有六種:"undefined"、"boolean"、"string"、"number"、"object"、"function"。
注意 typeof 對 null 會回傳 "object",這是語言設計上的歷史遺留,判斷 null 請直接用 value === null。
constructor:保存用於建立目前物件的函式hasOwnProperty("屬性名"):檢測屬性是否屬於實例本身,而非原型isPrototypeOf(物件名):檢測傳入物件是否為另一物件的原型toString():回傳物件的字串表示valueOf():回傳對應的原始值,通常與 toString 結果相同會先把運算元轉成布林值再取反:
== 會先進行型別轉換再比較;=== 則要求型別相同且值相等。實務上請一律使用 ===,可以避開大量難以察覺的型別轉換陷阱。
基本型別用 typeof:
var s = "ILoveYou"; var b = true; var i = 10; var u; var n = null; var o = new Object(); alert(typeof s); // "string" alert(typeof i); // "number" alert(typeof b); // "boolean" alert(typeof u); // "undefined" alert(typeof n); // "object" alert(typeof o); // "object"
參考型別則用 instanceof,回傳 true 或 false:
alert(person instanceof Object); // person 是 Object 嗎? alert(colors instanceof Array); // colors 是 Array 嗎? alert(pattern instanceof RegExp); // pattern 是 RegExp 嗎?
兩者分工不同:typeof 適合基本型別,instanceof 適合物件型別(它會沿著原型鏈往上找)。要判斷陣列時,更可靠的方式是 Array.isArray(value),因為 instanceof Array 在跨 iframe 的環境中可能失效。