js 判断变量的数据类型

js 里判断变量类型大概分为三种方法

1.  typeof   比较常用的

先排除几个特殊情况,之后的逻辑可能就能清晰点如下

1 // 特殊的基本数据类型判断
2 typeof null // 'object'
3 // 特殊的引入数据类型判断
4 typeof function () {} // 'function'
5 typeof new Function() // 'function'

剩下的就是基本数据类型会返回其数据类型,其他引用数据类型包括  new 关键字定义的变量,如下

 1 // 基本数据类型判断
 2 typeof 1 // 'number'
 3 typeof 'a' // 'string'
 4 typeof false // 'boolean'
 5 typeof undefined // 'undefined'
 6 typeof Symbol() // 'symbol'
 7 
 8 // 引用数据类型判断和new关键字创建的变量判断类型
 9 typeof {} // 'object'
10 typeof [] // 'object'
11 typeof new Number(1) // 'object'
12 typeof new String('a') // 'object'
13 typeof new Boolean(true) // 'object'
14 typeof new Number(1) // 'object'
15 typeof new Date() // 'object'
16 function Car () {} // 定义一个构造函数
17 typeof new Car() // 'object'

2,  instanceof 该方法是用来判断变量的原型链上层有没有等号右边的构造函数,不适用基本数据类型判断(number, string, boolean),如下  

1 function Car () {} // 定义一个构造函数
2 console.log(new Car() instanceof Car)
3 console.log({} instanceof Object) // true
4 console.log([] instanceof Array) // true
5 console.log(new String('') instanceof String) // true
6 console.log('' instanceof String) // false

3.  Object.prototype.toString.call()  刚知道这个方法,使用之后觉得还是很棒的

js 内置的数据类型和内置的对象都能判断出其类型,自定义的构造函数返回的是  [object Object] 

 1 Object.prototype.toString.call(null) // [object Null]
 2 Object.prototype.toString.call(undefined) // [object Undefined]
 3 Object.prototype.toString.call(1) // [object Number]
 4 Object.prototype.toString.call(new Number(1)) // [object Number]
 5 Object.prototype.toString.call('a') // [object String]
 6 Object.prototype.toString.call(new String('a')) // [object String]
 7 
 8 Object.prototype.toString.call({}) // [object Object]
 9 Object.prototype.toString.call([]) // [object Array]
10 Object.prototype.toString.call(new Date()) // [object Date]
11 Object.prototype.toString.call(/^d$/g) // [object RegExp]
12 Object.prototype.toString.call(() => {}) // [object Function]
13 Object.prototype.toString.call(new Function()) // [object Function]
14 
15 function Car () {} // 定义一个构造函数
16 Object.prototype.toString.call(new Car()) // [object Object]

以上

猜你喜欢

转载自www.cnblogs.com/blackbentel/p/11837487.html