JavaScript数据类型判断

JavaScript中有5种基本数据类型:undefined,String,Boolean,Number,Null,以及一种复杂数据类型Object。平常工做中常常会有判断数据类型的需求,这里简单介绍下我平时判断数据类型的几种方式。函数

1. typeof操做符

语法学习

typeof variable

对一个值使用typeof会返回以下字符串prototype

  • 'undefined' 这个值未定义
  • 'string' 这个值是字符串
  • 'object' 这个值是对象或者null
  • 'function' 这个值是函数
  • 'number' 这个值是数值
  • 'boolean' 这个值是布尔值

example:code

var a;
console.log(typeof a) // 'undefined'
var b = 123;
console.log(typeof b) // 'number'

typeof是一个操做符,并非做为全局对象的一个方法存在的,因此尽管能够像typeof(123)这样调用,但圆括号并非必须的。对象

2. instanceof操做符

当咱们检测的数据类型是基本类型的时候,typeof能很好的知足咱们的需求,但在检测引用类型的时候就显得有些力不从心了,一般咱们并非想知道某个值是对象,而是想知道它是什么类型的对象。所以,JavaScript提供了instanceof操做符。ip

语法原型链

result = variable instanceof constructor

若是这个值是给定引用类型的实例,那么instanceof操做符就会返回true,不然会返回false。开发

example:字符串

var obj = {};
console.log(obj instanceof Object); //true
console.log(obj instanceof RegExp); //false

当使用instanceof检测基本类型时,会始终返回false原型

3. Object.prototype.toString.call(data)

instanceof操做符确实解决了类型判断的问题,但仍是有一些不足之处。因为instanceof是根据数值原型链来识别数据类型的,可是JS中全部引用类型都是Object的实例,所以在检测一个引用类型的值与Object时,会始终返回true。此外,instanceof只能返回true/false,并不能直接返回数据的类型。所以,这里给你们介绍一种更直观的检测方式。

调用Object.prototypeto.String.call(data)会返回一个字符串,如

Object.prototype.toString.call(123) // "[object Number]"
Object.prototype.toString.call('123') // "[object String]"
Object.prototype.toString.call([123]) // "[object Array]"
Object.prototype.toString.call(/123/) // "[object RegExp]"

是否是很直观呢,为了方便使用,还能够作一些简单的处理,进一步的封装为一个函数,来供咱们在开发中使用。

function checkType(data) {
        return {}.toString.call(data).match(/[A-Z]\w+/)[0]
    };
    console.log(checkType(123))   // 'Number'
    console.log(checkType([123])) // 'Array'
    console.log(checkType(/123/)) // 'RegExp'
    console.log(checkType(null))  // 'Null'

4.小结

关于我在js中判断数据类型的方式,就到这里了。若是有什么其它的建议,欢迎指点,让你们互相交流,互相学习,一块儿进步!最后,祝你们节日快乐!

相关文章
相关标签/搜索