1. 数据类型及检测

173 阅读1分钟

数据类型

基本数据类型:

Symbol(ES6) String Boolean Number Undefined Null

引用数据类型:

Array Object 函数等(new Function() new Date()  new RegExp())

数据类型检测

1. typeof:返回表示数据类型的字符串

可以判定:symbol string boolean number undefined function
不能判定的: array object null 

2. instanceof:判断 A 是否为 B 的实例

缺点1:

(1 instanceof Number)   //false

(new Number(1) instanceof Number)  //true

缺点2:

([] instanceof Array)  // true

([] instanceof Object) // true

缺点3:

不能检测 null undefined

3. constructor:

缺点: null undefined无效

4. ===

主要用来区分null 和 undefined

5.Object.prototype.toString.call()

Object.prototype.toString.call('') //[object String]
Object.prototype.toString.call(1) // [object Number]
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(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]`
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]
Object.prototype.toString.call(window) ; //[object global] window是全局对象global的引用

特殊的检测:

Array.isArray([])  检测数组

参考链接

前端大全 - JavaScript 的数据类型及其检测