一 typeof

回顾:js有五种基本数据类型:值类型("number","string","boolean","undefined") 和引用类型 (“object”),其中“object” 又包含“array,function,null”等数据类型。

typeof 可以判断所有的值类型"number","string","boolean","undefined"和引用类型中的‘function’ 类型,其余所有的引用类型都只能返回‘object’。

typeof 能返回6中数据类型。

type of 1;//"number"
type of 'test';//"string"
type of true;//"boolean"
type of undefined;//"undefined"
type of console.log;//"function"
type of null;//"object"
type of [];//"object"
type of {};//"object"

二 instanceof

优点:可以判断某个对象是否是由某个构造函数new 出来的 ,凡是通过构造函数创建的都能进行判断

例如:

//构造函数假如被当作普通函数直接执行抛出错误
function Person (){
if(!(this instanceof Person)){ // 当Person被直接执行时,this在非严格模式下是指向window的,而被当作构造函数时,this 是指由Person new出来的对象
throw new Error(‘Person为构造函数,请使用 new Person’);
}
}

缺点:不能判断null 类型以及非new 出来的的值类型,不能精确的区分array、function和object

function utility(){
return {
isAarry:(data)=> data instanceof Array,
isFunction:()=> data instanceof Function
}
}

三 Object.prototype.toString

优点:所有的数据类型都能判断

原理:一切皆对象

js 里面还有好多类型判断 [object HTMLDivElement] div 对象 , [object HTMLBodyElement] body 对象 ,object Document或者 [object HTMLDocument](firefox,google) ......各种dom节点的判断,这些东西在我们写插件的时候都会用到。

function utility(){
return {
isArray:(o)=>Object.prototype.toString.call(o) == "[object Array]",
isObj:(o)=>Object.prototype.toString.call(o) == "[object Object]",
isNull:(o)=>Object.prototype.toString.call(o) == "[object Null]",
isFunction:(o)=>Object.prototype.toString.call(o) == "[object Function]",
isDate:(o)=>Object.prototype.toString.call(o) == "[object Date]",
isDocument:(o)=>Object.prototype.toString.call(o) =="[object Document]"|| Object.prototype.toString.call(o) == "[object HTMLDocument]",
isNumber:(o)=>Object.prototype.toString.call(o) == "[object Number]",
isString:(o)=>Object.prototype.toString.call(o) == "[object String]",
isUndefined:(o)=>Object.prototype.toString.call(o) == "[object Undefined]",
isBoolean:(o)=>Object.prototype.toString.call(o) == "[object Boolean]",
}
}

最新文章

  1. 行为驱动开发(BDD)实践示例
  2. 【系统篇】从int 3探索Windows应用程序调试原理
  3. SPSS数据分析—信度分析
  4. 【erlang】IPv6格式转IPv4
  5. C++C++ 指针(二)--c++ 指针(二)--c++
  6. iOS 最新版 CocoaPods 的安装使用
  7. Canvas前端游戏开发——FlappyBird详解
  8. row_number()、rank()、dense_rank()、ntile()
  9. JS实现全选,用于界面批量操作向后台传值时使用
  10. About struct in C
  11. ES6 浅谈let与const 块级作用域之封闭空间(闭包)
  12. WIN2003+IIS6+FastCGI+PHP5.3的安装配置
  13. SpringMVC配置多个数据源
  14. Android与js互相调用
  15. kubernetes 报错汇总
  16. 【原创】大叔问题定位分享(23)Ambari安装向导点击下一步卡住
  17. 开发问题及解决--java.lang.IllegalStateException: Circular dependencies cannot exist in RelativeLayout
  18. Two strings 的另一种解法
  19. 实时监听input输入的变化(兼容主流浏览器)【转】
  20. [转]linux(ubuntu)上运行网易popo

热门文章

  1. Activiti7 网关(排他网关)
  2. IDEA 2020 集成 Activity插件
  3. jmeter连接redis取数据
  4. vSphere Client上安装虚拟机工具VMware Tools
  5. svg的学习
  6. gcc g++ 安装与配置 入门详解 - 精简归纳
  7. uni-app开发注意事项
  8. python 进程(池)、线程(池)
  9. DevOps Next-AI / ML虚拟会议
  10. C++雾中风景15:聊聊让人抓狂的Name Mangling