JS判断数据类型的多种方式与区别

347 阅读2分钟

方法一: typeof 运算符

  typeof 操作符返回一个字符串,表示未经计算的操作数的类型,返回结果包括: "string"、"number"、"boolean"、"undefined"、"object"、"function"、"symbol" 七种类型。

    typeof NaN; // => 'number'
    typeof Infinity; // => 'number'
    typeof 1; // => 'number'

    typeof ''; // => 'string'

    typeof undefined; // => 'undefined'
    typeof true; // => 'boolean'

    typeof null; // => 'object'
    typeof []; // => 'object'

    function fn() {};
    typeof fn; // => 'function'

    typeof Symbol(); // => 'symbol'

    typeof new Date(); // => 'object'
    typeof new RegExp(); // => 'object'

  typeof 操作符在检测基本类型的时候在检测对象数据,包括数组,时间对象,正则对象时都返回'object',分类不够明细。

方法二: instanceof运算符

  instanceof运算符用于测试构造函数的prototype属性是否出现在对象的原型链中的任何位置。可以检测当前对象是否为某一对象的实例。不能用于检测基础数据类型,即非对象类型的不能检测。

    [] instanceof Array; // => true
    var o = {};
    o instanceof Object; // => true
    new Date() instanceof Date; // => true
    new RegExp() instanceof RegExp; // => true

方法三: constructor 属性

  constructor 返回创建实例对象的 Object 构造函数的引用。此属性的值是对函数本身的引用,而不是一个包含函数名称的字符串。与 instanceof 比较的类似,但是 constructor 可以进行基础数据类型的检测。在使用的时候有一点是需要注意的, constructor 的值是可以进行重写与覆盖的,所以检测的数据不一定准确。

    [].constructor === Array; // => true
    var o = {};
    o.constructor === Object; // => true
    ''.constructor === String;

方法四:Object.prototype.toString.call() 方法

  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 Undegined]'
    Object.prototype.toString.call(null); // => '[object Null]'
    Object.prototype.toString.call(new Function()); // => '[object Function]'
    Object.prototype.toString.call([]); // => '[object Array]'
    Object.prototype.toString.call(new RegExp()); // => '[object RegExp]'
    Object.prototype.toString.call({}); // => '[object Object]'
    Object.prototype.toString.call(new Date()); // => '[object Date]'

原文链接:JS判断数据类型的多种方式与区别