JavaScript的类型

原始类型:

  • number
  • string
  • boolean
  • null
  • undefined

对象类型:

  • Object

    • function
    • Array
    • Date
    • ...

隐式转换

+/- 运算

  • "37" + 7 = "377"
  • "37" - 7 = 30

== 运算

以下为true:

  • "1.23" == 1.23
  • 0 == false
  • null == undefined

比较运算

===严格等于

  • 类型不同,返回false
  • 类型相同,以下为true:
    • null === null
    • undefine === null
    • NaN != NaN
    • new Object != new Obejct

==等于

  • 类型相同,同===
  • 类型不同,尝试类型转换比较
    • null == undefined
    • number == string 转number
    • boolean == ? 转number
    • Object == number | string 尝试对象转换为基本类型
    • 其他:false

包装类型

为了便于操作基本类型值,Js提供了基本类型的自动包装功能,每单读取一个基本类型值的时候,后台就会创建一个对应的基本包装类型的对象,并在调用后自动销毁。

由于基本包装类型和基本类型的含义并不一样,会导致typeof等操作产生不同的结果,不推荐显示实例化基本数据类型

var a = "string";
alert(a.length); //6 a.t = 3;
alert(a.t); //undefined

类型检测

typeof

以下为true:

typeof 100 === “number”
typeof true === “boolean”
typeof function () {} === “function”
typeof(undefined) ) === “undefined”
typeof(new Object() ) === “object”
typeof( [1, 2] ) === “object”
typeof(NaN ) === “number” //NaN也为number
typeof(null) === “object”

instanceof

obj instanceof Object 利用原型链进行判断,适用于对象间判断。它期望左边是一对象,右边是函数对象或函数构造器。

以下为true:

[1, 2] instanceof Array === true
new Object() instanceof Array === false

Object.prototype.toString.apply()

Object.prototype.toString.apply([]); === “[object Array]”;
Object.prototype.toString.apply(function(){}); === “[object Function]”;
Object.prototype.toString.apply(null); === “[object Null]”
Object.prototype.toString.apply(undefined); === “[object Undefined]” // IE6/7/8 Object.prototype.toString.apply(null) 返回”[object Object]”

小结

  • typeof

    适合基本类型及function检测,遇到null失效。

  • [[Class]]

    通过{}.toString拿到,适合内置对象和基元类型,遇到null和undefined失效(IE678等返回[object Object])。

  • instanceof

    适合自定义对象,也可以用来检测原生对象,在不同iframe和window间检测时失效。

最新文章

  1. 开源:ASP.NET Aries 开发框架
  2. test 2016-12-28
  3. React JSX语法说明
  4. Swift语法简介(一)
  5. WPF自定义控件与样式(9)-树控件TreeView与菜单Menu-ContextMenu
  6. (五)Super VLAN
  7. IOS开发--数据持久化篇之文件存储(一)
  8. 国外程序员整理的Java资源
  9. tomcat 6 不支持jsf2.2,仅支持jsf2.0及以下版本
  10. PHP 编译问题PEAR package PHP_Archive not installed的解决
  11. python2.6升级到2.7
  12. 数据结构之计算器的实现(JAVA)(四)
  13. 一个不错的windows编程网址
  14. javaIO操作之字节输入流--InputStream
  15. RocketMQ4.3.x对顺序消息的理解
  16. 图示Java类的初始化顺序
  17. 在CentOS 7上部署Ghost博客
  18. Windows 7 改造
  19. 使用Java+MySQL+Apache开发后台项目(一)
  20. IDEA新建模块

热门文章

  1. Composer使用笔记
  2. 苹果快速的修复了Mac OS High Sierra 上出现了root的漏洞
  3. PHP+Redis 实例【二】页面缓存 新玩法
  4. Class 与 Style 绑定
  5. jstl--->Core 核心标签库->URL操作
  6. jQuery开发自定义插件 $.extend()与$.fn.extend()
  7. Spring Cloud 之 Feign
  8. 【NOIP2015提高组】子串
  9. node-koa搭建MVC/RESTful API项目
  10. 酷狗歌曲缓存kgtemp转mp3工具