美文网首页
检测JS数据类型的四种方法

检测JS数据类型的四种方法

作者: 追马的时间种草 | 来源:发表于2019-08-20 22:36 被阅读0次

上一篇:数组方法汇总


数据类型分类:

检测方法:

  • type of
    对基本数据类型(null除外)和es6的Symbol还有Function有效,其余都无效检测类型都是object
typeof ''; // string 有效
typeof 1; // number 有效
typeof Symbol(); // symbol 有效
typeof true; //boolean 有效
typeof undefined; //undefined 有效
typeof null; //object 无效
typeof [] ; //object 无效
typeof function(){}; // function 有效
typeof new Date(); //object 无效
typeof new RegExp(); //object 无效
  • instanceof :关于原理,建议先去了解一下原型及原型链

    用途:检测 A是否是B的实例
    用法:A instanceof B
    返回值: true || false

  //当 A 的 __proto__ 指向 B 的 prototype 时,就认为 A 就是 B 的实例
[] instanceof Array; // true
{} instanceof Object;// true
new Date() instanceof Date;// true
 
function Person(){};
new Person() instanceof Person;
 
[] instanceof Object; // true
new Date() instanceof Object;// true
new Person instanceof Object;// true
  • constructor
    用途:判断A作为构造函数是否遗传给了a,a的构造函数是否是A。
    用法: f.constructor == F
    返回值:true || false
    如图:
    constructor检测
  • Object.prototype.toString.call()可用于所有的数据类型检测
    缩写:toString.call()
toString.call('') ;   // [object String]
toString.call(1) ;    // [object Number]
toString.call(true) ; // [object Boolean]
toString.call(Symbol()); //[object Symbol]
toString.call(undefined) ; // [object Undefined]
toString.call(null) ; // [object Null]
toString.call(new Function()) ; // [object Function]
toString.call(new Date()) ; // [object Date]
toString.call([]) ; // [object Array]
toString.call(new RegExp()) ; // [object RegExp]
toString.call(new Error()) ; // [object Error]
toString.call(document) ; // [object HTMLDocument]
toString.call(window) ; //[object global] window 是全局对象 global 的引用

相关文章

  • JavaScript数据类型检测总结

    在js中,有四种用于检测数据类型的方式,分别是: typeof用来检测数据类型的运算符 instanceof 检...

  • JavaScript数据类型检测总结

    在js中,有四种用于检测数据类型的方式,分别是: typeof用来检测数据类型的运算符 instanceof 检...

  • 2017-12-26

    js中判断数据类型的几种方法(一) js中可以判断数据类型的方法有四种:typeof、toString、const...

  • JS数据类型检测

    之前有讲过JS数据类型,但是怎么判断到底是某个数据是什么数据类型?今天就来讲一下。JS数据类型检测常用的主要有四种...

  • 原生Js数据类型及操作知识点总结

    原生Js的数据类型总结 1.基本数据类型与其检测方法 String,Undefined,Boolean,null,...

  • 三、JS 进阶--判断 JS 的数据类型

    判断 JS 的数据类型 判断 JS 数据类型,也就是我们说的类型检测,本文提供五种方法,分别是 typeof 运算...

  • 三、JS 进阶--判断 JS 的数据类型

    判断 JS 的数据类型 判断 JS 数据类型,也就是我们说的类型检测,本文提供五种方法,分别是 typeof 运算...

  • JS 数据类型的四种检测方法

    简介 我们在代码中经常要对数据类型进行判断,大家熟知的应该是 typeof,那么它有什么不足,有没有其他方法来进行...

  • 检测JS数据类型的四种方法

    上一篇:数组方法汇总 数据类型分类: 检测方法: type of 对基本数据类型(null除外)和es6的Sym...

  • 判断JS数据类型的四种方法

    这篇文章 判断JS数据类型的四种方法 写的非常好。 个人总结:最好的方法是使用 Object.prototype....

网友评论

      本文标题:检测JS数据类型的四种方法

      本文链接:https://www.haomeiwen.com/subject/dqmpsctx.html