Object.prototype.toString.call 与数组判断
2013-08-26 11:41
561 查看
为什么要用Object.prototype.toString而不是Function.prototype.toString或者其它?这是和他们的toString解释方式有关系的。下面是ECMA中对Object.prototype.toString的解释:
其过程简单说来就是:1、获取对象的类名(对象类型)。2、然后将[object、获取的类名、]组合并返回。
ECMA中对Array有如下说明:
因此我们用如下代码来检测数组:
这种方式既解决了instanceof存在的跨页面问题,也解决了属性检测方式所存在的问题,实在是一种妙招,一个很好的解决方案。
除此之外,这种解决办法也可以应用于判断Date,Function等类型的对象。
Object.prototype.toString( ) When the toString method is called, the following steps are taken: 1. Get the [[Class]] property of this object. 2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]”. 3. Return Result (2)
其过程简单说来就是:1、获取对象的类名(对象类型)。2、然后将[object、获取的类名、]组合并返回。
ECMA中对Array有如下说明:
The [[Class]] property of the newly constructed object is set to “Array”.
因此我们用如下代码来检测数组:
function isArray(o) { return Object.prototype.toString.call(o) === '[object Array]'; }
这种方式既解决了instanceof存在的跨页面问题,也解决了属性检测方式所存在的问题,实在是一种妙招,一个很好的解决方案。
除此之外,这种解决办法也可以应用于判断Date,Function等类型的对象。
相关文章推荐
- Object.prototype.toString.call 与数组判断
- js进行类型判断 Object.prototype.toString.call()
- 判断一个变量的类型Object.prototype.toString.call
- typeof 和 Object.prototype.toString.call 数据类型判断的区别
- Object.prototype.toString.call()进行类型判断
- 【JavaScript】Object.prototype.toString.call()进行类型判断
- Object.prototype.toString.call()进行类型判断
- JavaScript中使用Object.prototype.toString判断是否为数组
- js判断对象类型 typeof与Object.prototype.toString.call方法的区别
- Object.prototype.toString.call()进行类型判断
- Object.prototype.toString.call() 区分对象类型(判断对象类型)
- 通过 Object.prototype.toString.call() 进行类型判断
- 通过 Object.prototype.toString.call() 进行类型判断
- js中利用Object.prototype.toString.call()判断数据类型
- 通过Object.prototype.toString.call()--判断数据(基本、引用)类型
- Object.prototype.toString.call() 进行类型判断
- 通过 Object.prototype.toString.call() 进行类型判断
- js中精确判断对象类型--关于typeof 和Object.prototype.toString方法的区别
- Object.prototype.toString.call()方法浅谈
- js中toStirng()与Object.prototype.toString.call()方法理解