javascript中判断数据类型的四种方法及typeof、instanceof、constructor、toString
来源:互联网 发布:3d格斗类网络游排行榜 编辑:程序博客网 时间:2024/05/18 01:42
在 ECMAScript 规范中,共定义了 6种数据类型,分为 基本类型 和 引用类型 两大类,如下所示:
基本类型(简单类型):String、Number、Boolean、Undefined、Null 。由于其占据空间固定,是简单的数据段,为了便于提升变量查询速度,将其存储在栈中,即按值访问。
引用类型(复杂类型):Object。由于其值的大小会改变,所以不能将其存放在栈中,否则会降低变量查询速度,因此,其值存储在堆(heap)中,而存储在变量处的值,是一个指针,指向存储对象的内存处,即按址访问。引用类型除 Object 外,还包括 Function 、Array、RegExp、Date 等等。
鉴于 ECMAScript 是松散类型的,因此需要有一种手段来检测给定变量的数据类型,对于这个问题,JavaScript 也提供了多种技术方案,但遗憾的是,不同的方案得到的结果也参差不齐。
下面介绍常用的四种方案,并对各个方案存在的问题进行简单的分析。
1.typeof
typeof 是一个操作符,其右侧跟一个一元表达式,并返回这个表达式的数据类型。返回的结果用该类型的字符串(全小写字母)形式表示,包括以下 6 种:number、boolean、string、object、
undefined、function 。typeof ''; // string 有效typeof 1; // number 有效typeof Symbol(); // symbol 有效typeof true; //boolean 有效typeof undefined; //undefined 有效typeof null; //object 无效typeof [] ; //object 无效typeof new Function(); // function 有效typeof new Date(); //object 无效typeof new RegExp(); //object 无效
有些时候,typeof 操作符会返回一些令人迷惑但技术上却正确的值:
- 对于基本类型,除 null 以外,均可以返回正确的结果。
- 对于引用类型,除 function 以外,一律返回 object 类型。
- 对于 null ,返回 object 类型。
- 对于 function 返回 function 类型。
其中,null 有属于自己的数据类型 Null , 引用类型中的 数组、日期、正则 也都有属于自己的具体类型,而 typeof 对于这些类型的处理,只返回了处于其原型链最顶端的 Object 类型,没有错,但不是我们想要的结果。
2.instanceof
instanceof 是用来判断 A 是否为 B 的实例,表达式为:A instanceof B,如果 A 是 B 的实例,则返回 true,否则返回 false。 在这里需要特别注意的是:instanceof 检测的是原型。
我们用一段伪代码来模拟其内部执行过程:
instanceof (A,B) = { var L = A.__proto__; var R = B.prototype; if(L === R) { //A的内部属性__proto__指向B的原型对象 return true; } return false;}
从上述过程可以看出,当 A 的 proto 指向 B 的 prototype 时,就认为 A 就是 B 的实例,我们再来看几个例子:
[] instanceof Array; //true{} instanceof Object;//truenew Date() instanceof Date;//truefunction Person(){};new Person() instanceof Person;[] instanceof Object; //truenew Date() instanceof Object;//truenew Person instanceof Object;//true
我们发现,虽然 instanceof 能够判断出 [ ] 是Array的实例,但它认为 [ ] 也是Object的实例,为什么呢?
我们来分析一下 [ ]、Array、Object 三者之间的关系:
从 instanceof 能够判断出 [ ].proto 指向 Array.prototype,而 Array.prototype.proto 又指向了Object.prototype,最终 Object.prototype.proto 指向了null,标志着原型链的结束。因此,[]、Array、Object 就在内部形成了一条原型链:
从原型链可以看出,[] 的 proto 直接指向Array.prototype,间接指向 Object.prototype,所以按照 instanceof 的判断规则,[] 就是Object的实例。依次类推,类似的 new Date()、new Person() 也会形成一条对应的原型链 。因此,instanceof 只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类型。
instanceof 操作符的问题在于,它假定只有一个全局执行环境。如果网页中包含多个框架,那实际上就存在两个以上不同的全局执行环境,从而存在两个以上不同版本的构造函数。如果你从一个框架向另一个框架传入一个数组,那么传入的数组与在第二个框架中原生创建的数组分别具有各自不同的构造函数。
为了解决这个问题, ECMAScript 5 新增了 Array.isArray() 方法。这个方法的目的是最终确定某个值到底是不是数组,而不管它是在哪个全局执行环境中创建的。这个方法的用法如下。
Array.isArray(obj)
if (Array.isArray(value)){ //对数组执行某些操作}
如下面实例:
// 下面的函数调用都返回 trueArray.isArray([]);Array.isArray([1]);Array.isArray(new Array());// 鲜为人知的事实:其实 Array.prototype 也是一个数组。Array.isArray(Array.prototype); // 下面的函数调用都返回 falseArray.isArray();Array.isArray({});Array.isArray(null);Array.isArray(undefined);Array.isArray(17);Array.isArray('Array');Array.isArray(true);Array.isArray(false);Array.isArray({ __proto__: Array.prototype });
支持 Array.isArray()方法的浏览器有 IE9+、 Firefox 4+、 Safari 5+、 Opera 10.5+和 Chrome。
当检测Array实例时, Array.isArray 优于 instanceof,因为Array.isArray能检测iframes.
var iframe = document.createElement('iframe');document.body.appendChild(iframe);xArray = window.frames[window.frames.length-1].Array;var arr = new xArray(1,2,3); // [1,2,3]// Correctly checking for ArrayArray.isArray(arr); // true// Considered harmful, because doesn't work though iframesarr instanceof Array; // false
假如不存在 Array.isArray(),则在其他代码之前运行下面的代码将创建该方法。
if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; };}
3.constructor
当一个函数 F被定义时,JS引擎会为F添加 prototype 原型,然后再在 prototype上添加一个 constructor 属性,并让其指向 F 的引用。如下所示:
当执行 var f = new F() 时,F 被当成了构造函数,f 是F的实例对象,此时 F 原型上的 constructor 传递到了 f 上,因此 f.constructor == F
可以看出,F 利用原型对象上的 constructor 引用了自身,当 F 作为构造函数来创建对象时,原型上的 constructor 就被遗传到了新创建的对象上, 从原型链角度讲,构造函数 F 就是新对象的类型。这样做的意义是,让新对象在诞生以后,就具有可追溯的数据类型。
同样,JavaScript 中的内置对象在内部构建时也是这样做的:
细节问题:
- null 和 undefined 是无效的对象,因此是不会有 constructor 存在的,这两种类型的数据需要通过其他方式来判断。
函数的 constructor 是不稳定的,这个主要体现在自定义对象上,当开发者重写 prototype 后,原有的constructor 引用会丢失,constructor 会默认为 Object
为什么变成了 Object?
因为 prototype 被重新赋值的是一个 { }, { } 是 new Object() 的字面量,因此 new Object() 会将 Object 原型上的 constructor 传递给 { },也就是 Object 本身。
4.toString
toString 是 Object 原型对象上的方法,使用 call 来调用该方法会返回调用者的类型字符串,格式为 [object,xxx],xxx 是调用者的数据类型,包括:String、Number、Boolean、Undefined、Null、Function、Date、Array、RegExp、Error、HTMLDocument 等, 基本上,所有的数据类型都可以通过这个方法获取到。
Object.prototype.toString.call('') ; // [object String]Object.prototype.toString.call(1) ; // [object Number]Object.prototype.toString.call(true) ; // [object Boolean]Object.prototype.toString.call(Symbol()); //[object Symbol]Object.prototype.toString.call(undefined) ; // [object Undefined]Object.prototype.toString.call(null) ; // [object Null]Object.prototype.toString.call(new Function()) ; // [object Function]Object.prototype.toString.call(new Date()) ; // [object Date]Object.prototype.toString.call([]) ; // [object Array]Object.prototype.toString.call(new RegExp()) ; // [object RegExp]Object.prototype.toString.call(new Error()) ; // [object Error]Object.prototype.toString.call(document) ; // [object HTMLDocument]Object.prototype.toString.call(window) ; //[object global] window是全局对象 global 的引用
需要注意的是,必须通过 call 或 apply 来调用,而不能直接调用 toString , 从原型链的角度讲,所有对象的原型链最终都指向了 Object, 按照JS变量查找规则,其他对象应该也可以直接访问到 Object 的 toString方法,而事实上,大部分的对象都实现了自身的 toString 方法,这样就可能会导致 Object 的 toString 被终止查找,因此要用 call/apply 来强制调用Object 的 toString 方法。
- javascript中判断数据类型的四种方法及typeof、instanceof、constructor、toString
- typeof + instanceof+toString+constructor是如何判断javascript数据类型的
- js中判断数据类型的属性typeof、instanceof、 constructor、 prototype
- javascript类型判断 typeof instanceof constructor
- javascript类型判断 typeof instanceof constructor
- js中判断一个对象的类型的方法typeof/constructor/instanceof
- JavaScript 中typeof、instanceof 与 constructor 的区别?
- 如何判断js中的数据类型:typeof、instanceof、 constructor、 prototype方法比较
- typeof,instanceof,Object.prototype.toString来判断数据类型
- typeof constructor instanceof 判断类型
- javascript之typeof、constructor、instanceof
- Javascript中数据类型及其判别方法(typeof instanceof Object.prototype.toSting.call(obj)的区别)
- JavaScript 中 typeof 和 instanceof 的区别及如何判断数组
- 判断变量的类型(typeof、instanceof、Object.prototype.toString)
- javascript封装判断全数据类型方法, toString方法, 对象的枚举(in, instanceof, hasOwnProperty的用法), arguments类数组属性
- 判断数据类型:typeof和instanceof
- JavaScript中判断数据类型的四种方法
- javascript 理解 typeof, instanceof and constructor
- org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'faceAction' must be of
- 整理的对我有帮助的博文
- IO流
- 跨域概念
- 让流程保持健康?删除!
- javascript中判断数据类型的四种方法及typeof、instanceof、constructor、toString
- SKILLCAD v41R Linux64 1CD+Keyshot Pro v7.0.438
- 数据结构 第15讲 一场说走就走的旅行——最短路径
- 最常用的PHP正则表达式收集整理
- tornado 多线程服务器配置
- 安卓MVP设计模式
- Qualcomm最新推出的神经处理引擎
- 2018 js教学难点汇集
- L2-005. 集合相似度