js的变量是松散类型的,所以需要检测变量数据类型的方法。
1. typeof运算符
使用typeof来检测是一种基本的方法,typeof操作符可能返回的值有:
- 'undefined'——未定义
- 'boolean'——布尔值
- 'string'——字符串
- 'number'——数值
- 'object'——对象或null
- 'function'——函数
如下测试:
| 测试 | 输出 |
|---|---|
| typeof 233 | number |
| typeof null | object |
| typeof {} | object |
| typeof [] | ** object** |
| typeof (function(){}) | function |
| typeof undefined | undefined |
| typeof '233' | string |
| typeof true | boolean |
2. instanceof
typeof操作符存在的缺陷是无法具体的判断object的类型。对此,提出instanceof。
instanceof主要用于检测一个实例是否属于一个类。
如下检测:
| 测试 | 输出 |
|---|---|
| [] instanceof Array | true |
| /^$/ instanceof RegExp | true |
| [] instanceof Object | true |
针对这种方法,我还可以使用类似的原理constructor来检测,如下:
| 测试 | 输出 |
|---|---|
| [].constructor === Array | true |
| [].constructor === Object | false |
| {}.constructor === Object | true |
注意:我们的constructor可以避免instanceof检测的时候,用Object也是true的问题
3. Object.prototype.toString.call(value)
上面的方法我们很常见,下面记录以下最近了解到的一种新方法。
Object.prototype.toString.call(value)是对象的一个原生原型扩展函数,用来更精确的区分数据类型。如下:
var gettype=Object.prototype.toString
gettype.call('233')输出 [object String]
gettype.call(233) 输出 [object Number]
gettype.call(true) 输出 [object Boolean]
gettype.call(undefined) 输出 [object Undefined]
gettype.call(null) 输出 [object Null]
gettype.call({}) 输出 [object Object]
gettype.call([]) 输出 [object Array]
gettype.call(function(){}) 输出 [object Function]