手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >JavaScript中使用Object.prototype.toString判断是否为数组
JavaScript中使用Object.prototype.toString判断是否为数组
摘要:为什么要用Object.prototype.toString而不是Function.prototype.toString或者其它?这是和他们...

为什么要用Object.prototype.toString而不是Function.prototype.toString或者其它?这是和他们的toString解释方式有关系的。下面是ECMA中对Object.prototype.toString的解释:

复制代码 代码如下:

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等类型的对象。

另外还有几个方法:

复制代码 代码如下:

var arr = []; return arr instanceof Array;

如果有其他好的方法不妨贴出来。

【JavaScript中使用Object.prototype.toString判断是否为数组】相关文章:

JavaScript中的acos()方法使用详解

JavaScript中length属性的使用方法

JavaScript中的异常处理方法介绍

JavaScript中for循环的使用详解

JavaScript中用于四舍五入的Math.round()方法讲解

在JavaScript中使用NaN值的方法

JavaScript中Number.MAX_VALUE属性的使用方法

JavaScript中的bold()方法使用详解

在JavaScript中正确引用bind方法的应用

JavaScript中this关键字使用方法详解

精品推荐
分类导航