寫法:
if (typeof 變量 == "類型標識") { ... }
常見值的對照:
| 值 | typeof 結果 |
|---|---|
| {an:"object"} | object |
| ["an","array"] | object |
| function() {} | function |
| "a string" | string |
| 55 | number |
| true | boolean |
| new User() | object |
問題很明顯:陣列、物件、自訂類別的實例,typeof 一律回傳 object。用它無法分辨手上這東西到底是 Object、Array 還是 User。
寫法:
if (變量.constructor == "類型標識符") { ... }
| 值 | constructor 結果 |
|---|---|
| {an:"object"} | Object |
| ["an","array"] | Array |
| function() {} | Function |
| "a string" | String |
| 55 | Number |
| true | Boolean |
| new User() | User |
用 constructor 能正確取得每一種資料的型別,所以需要精確判斷時,優先用 constructor。
判斷「是否為 undefined」時,typeof 反而是最方便的:
if (typeof 變量 == "undefined") { ... }
原因是直接寫 變量 === undefined 在變數完全未宣告時會拋出 ReferenceError,而 typeof 是唯一能安全探測未宣告識別符的運算子。
Array.isArray(arr),它跨 iframe 也有效,而 constructor == Array 在不同 frame 之間會失效。Object.prototype.toString.call(x) 會回傳 "[object Array]" 這類結果,是最可靠的手段。typeof null === "object" 是語言本身的歷史遺留,判斷 null 請直接寫 x === null。obj.constructor,因此它不是百分之百可靠的依據。