JavaScript 语言的每个值,都属于某一种数据类型
原始类型数组
特殊值函数
复杂类型prototype
1.typeof 运算符code
typeof 运算符能够返回一个值的数据类型。
typeof true // "boolean" typeof 100 // "number" typeof 'Hello World' // "string" var fn = function() { console.log(str); } typeof fn // "function" var u; typeof u // "undefined" // 因为历史缘由,null 的类型是 object typeof null // "object" typeof window // "object" typeof {} // "object" typeof [] // "object"
2.instanceof 运算符对象
instanceof 运算符返回一个布尔值,表示对象是否为某个构造函数的实例。
instanceof 运算符的左边是实例对象,右边是构造函数。它会检查右边构建函数的原型对象(prototype),是否在左边对象的原型链上。ip
// instanceof 运算符只能用于对象,不适用原始类型的值以及undefined,null var s = 'hello' s instanceof String // false
instanceof 的用处原型链
var x = [1, 2, 3]; var y = {}; var date = new Date(); x instanceof Array // true y instanceof Object // true date instanceof Date // true
3.Object.prototype.toString 方法字符串
Object.prototype.toString.call(value)
Object.prototype.toString.call(1) // "[object Number]" Object.prototype.toString.call('') // "[object String]" Object.prototype.toString.call(true) // "[object Boolean]" Object.prototype.toString.call(undefined) // "[object Undefined]" Object.prototype.toString.call(null) // "[object Null]" Object.prototype.toString.call(Math) // "[object Math]" Object.prototype.toString.call({}) // "[object Object]" Object.prototype.toString.call([]) // "[object Array]"
利用这个特性,能够写出typeof运算符更准确的类型判断函数原型
var type = function (o){ var s = Object.prototype.toString.call(o); return s.match(/\[object (.*?)\]/)[1].toLowerCase(); }; type({}); // "object" type([]); // "array" type(5); // "number" type(null); // "null" type(); // "undefined" type(/abcd/); // "regex" type(new Date()); // "date"