JavaScript有三種方法,可以確定一個值到底是什么類型横腿。
- typeof
- instanceof
- Object.prototype.toString
1. typeof
數(shù)值碱茁、字符串官脓、布爾值分別返回number、string前标、boolean坠韩。
typeof 123 // "number"
typeof '123' // "string"
typeof false // "boolean"
函數(shù)
function f() {}
typeof f
// "function"
undefined
function f() {}
typeof f
// "function"
// 錯誤的寫法
if (v) {
// ...
}
// ReferenceError: v is not defined
// 正確的寫法
if (typeof v === "undefined") {
// ...
}
其他
typeof window // "object"
typeof {} // "object"
typeof [] // "object"
typeof null // "object"
var o = {};
var a = [];
o instanceof Array // false
a instanceof Array // true