博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
js中的数据类型及判断方法
阅读量:6953 次
发布时间:2019-06-27

本文共 2090 字,大约阅读时间需要 6 分钟。

ECMAScirpt 变量有两种不同的数据类型:基本类型,引用类型。

基本类型

● Boolean

● Null
● Undefined
● Number
● String
● Symbol (ECMAScript 6 新定义)

对象类型

● Object

对象类型涵盖了很多引用类型,任何非基本类型的都是对象类型。如Function、Array、Date,这里就不在赘述。

两种类型的区别

可变性

基本类型:不可变类型,无法添加属性;即使添加属性,解析器无法再下一步读取它;

var cat = "cat";cat.color = "black";cat.color  // undefined

对象类型:可变类型,支持添加和删除属性。

比较和传递

基本类型:按值比较,按值传递;

对象类型:按引用比较,按引用传递。

// 基本类型var cat = "tom";var dog = "tom";cat === dog // true//对象类型var cat = {name:"tom"};var dog = {name:"tom"};cat === dog //false

如何判断数据类型

有四种方法:typeof、instanceof、 constructor、 prototype

例如:

var a = "abcdef";var b = 12345;var c= [1,2,3];var d = new Date();var e = function(){ console.log(111); };var f = function(){ this.name="cat"; };

最常见的判断方法:typeof

alert(typeof a)   ------------> stringalert(typeof b)   ------------> numberalert(typeof c)   ------------> objectalert(typeof d)   ------------> objectalert(typeof e)   ------------> functionalert(typeof f)   ------------> function

其中typeof返回的类型都是字符串形式,需注意,例如:

alert(typeof a == "string") -------------> truealert(typeof a == String) ---------------> false

另外typeof 可以判断function的类型;在判断除Object类型的对象时比较方便。

判断已知对象类型的方法: instanceof

alert(c instanceof Array) ---------------> truealert(d instanceof Date) ---------------> true alert(f instanceof Function) ------------> truealert(f instanceof function) ------------> false

注意:instanceof 后面一定要是对象类型,并且大小写不能错,该方法适合一些条件选择或分支。

根据对象的constructor判断: constructor

alert(c.constructor === Array) ----------> truealert(d.constructor === Date) -----------> truealert(e.constructor === Function) -------> true

注意: constructor 在类继承时会出错

通用但很繁琐的方法: prototype

console.log(Object.prototype.toString.call(a)) -------> [object String];console.log(Object.prototype.toString.call(b)) -------> [object Number];console.log(Object.prototype.toString.call(c)) -------> [object Array];console.log(Object.prototype.toString.call(d)) -------> [object Date];console.log(Object.prototype.toString.call(e)) -------> [object Function];console.log(Object.prototype.toString.call(f)) -------> [object Function];

注意大小写。

转载于:https://www.cnblogs.com/cckui/p/7524585.html

你可能感兴趣的文章
Allegro16.6导出位号图
查看>>
mycat err:java.sql.SQLNonTransientException: find no Route:select日志报错
查看>>
Centos7.4源码搭建zabbix3.4.11企业级监控
查看>>
yumi引导盘制作
查看>>
Objective C类方法load和initialize的区别
查看>>
【高德地图API】从零开始学高德JS API(五)路线规划——驾车|公交|步行
查看>>
LINUX中nagios客户端安装步骤及遇到问题
查看>>
CentOS6.7系统优化加强牢固脚本
查看>>
nofollow是什么意思?nofollow标签的写法和作用
查看>>
MySQL常用命令收录
查看>>
SQL 删除数据-select在当前表字段作为条件
查看>>
nike roshe run homme pas cher
查看>>
webrtc研究资源摘录
查看>>
.Net Micro Framework移植基础(包编译通过)
查看>>
对象和实例的区别
查看>>
关于MARATHON和容器的端口映射
查看>>
php通过header发送自定义数据
查看>>
云时代必备 CDN 技能包
查看>>
仿大众点评下拉菜单实现
查看>>
数据库事务隔离级别-- 脏读、幻读、不可重复读(清晰解释)
查看>>