【01】判断某个对象是否是数组?

判断某个对象是否是数组?

01, typeof 
对于Function, String, Number ,Undefined 等几种类型的对象来说,可以胜任。
var arr=new Array("1","2","3","4","5");
alert(typeof(arr));//object
但是,对于Array不行。




02,instanceOf
返回一个 Boolean 值,指出对象是否是特定类的一个实例。 

使用方法:result = object instanceof class,成功的返回 true。
var arrayStr=new Array("1","2","3","4","5");
if (arrayStr instanceof Array){//对数组执行某些操作


instanceof 操作符的问题在于,它对单一的全局执行环境有效 多个frame中就会有问题了。

如果网页中包含多个框架,那实际上就存在两个以上不同的全局执行环境,从而存在两个以上不同版本的 Array 构造函数。

如果你从一个框架向另一个框架传入一个数组,那么传入的数组与在第二个框架中原生创建的数组分别具有各自不同的构造函数。




03,利用原型。

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)

规范定义了Object.prototype.toString的行为:
首先,取得对象的一个内部属性[[Class]],然后依据这个属性,返回一个类似于"[object Array]"的字符串作为结果。
(看过ECMA标准的应该都知道,[[]]用来表示语言内部用到的、外部不可直接访问的属性,称为“内部属性”)。
利用这个方法,再配合call,我们可以取得任何对象的内部属性[[Class]],然后把类型检测转化为字符串比较。

ECMA-262 写道
new Array([ item0[, item1 [,…]]])
The [[Class]] property of the newly constructed object is set to “Array”。

function isArray(obj) {  
  return Object.prototype.toString.call(obj) === '[object Array]';   
}



04,Array.isArray(obj);

  • 是ES5方法。
  • 支持的浏览器有IE9+、Firefox 4+、Safari 5+、Opera 10.5+和Chrome

【】
if (Array.isArray(value)){//对数组执行某些操作}



05,ES3中isArray()的兼容性写法:
var isArray = Array.isArray || function(o) {
    return typeof o === "object" &&  Object.prototype.toString.call(o) === "[object Array]";
};







**

猜你喜欢

转载自www.cnblogs.com/moyuling/p/9019163.html