首页 > javascript中Array的类型为什么是object?

javascript中Array的类型为什么是object?

例如如下代码

console.log(typeof(new Array()));
console.log(typeof([]));

它们的输出都是object,为什么不是array呢?那么我们怎么判断一个对象是普通的object还是array类型呢?


我还见过一种比较巧妙的判断方法

console.log(Object.prototype.toString.call([]));

它会输出[object Array],这样你就可以判断它的类型了


typeof可以检测基本类型包括 undefined, string, number, boolean,但是对于检测对象就不靠谱了。不只是Array,javascript中的对象,包括 Date, String, Boolean, Number, Object, Function, Array, RegExp, Error 使用typof只会返回 "object"。

使用 instanceof 或者 constructor 来检测 Array 也不是靠谱的办法。如果是待检测的数组来自一个iframe的数组时,instanceof和contructor都会失效。由于每个iframe都有一套自己的执行环境,跨frame实例化的对象彼此是不共享原型链的。

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]    
  arr instanceof Array; // false    
  arr.constructor === Array; // false

ECMA中对Object.prototype.toString的解释:

When the toString method is called, the following steps are taken:
1. Get the http://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 http://Class property of the newly constructed object is set to “Array”.
其他对象类似。

因此使用这种方法既解决了instanceof存在的跨页面问题,也解决了属性检测方式所存在的问题。

另外,使用Object.prototype.toString,而不是Object.toString是因为toString可能被覆写。

var type=function(object){
return Object.prototype.toString.call(object);
}

type({}) //"[object Object]"
type([1,2,3,4]); //"[object Array]"
type(new Date()); //"[object Date]"
type(/^hello/); //"[object RegExp]"
type(new Error()) //"[object Error]"
type(new Number()) //"[object Number]"
//......

在ECMA中,除了Number,String,null,undefined,Boolean,其它的实例都会归为object。而创建Function或者Array这些类型的实例的时候,其实都是基于Object实例进行的一种扩展。只是多了一些特有属性。判断一个对象是一个数组还是普通的Object可以使用Array.isArray的方法。然而这个方法会因为在跨iframe的情况下失效。最简单的办法是Object.prototype.toString.call(array)的方式。因为只有通过Object的原型的toString方法才能拿到每个实例的[class]内部属性。这些内容都能到ECMA5.1的官方文档找到哈。


参考jQuery的解决方案

var class2type = {};
    $.each("Boolean Number String Function Array Date RegExp Object".split(" "), function (i, name) {
        class2type[ "[object " + name + "]" ] = name.toLowerCase();
    });
    $.type = function (obj) {
        return obj == null ?
            String(obj) : class2type[ toString.call(obj) ] || "object"
    };
【热门文章】
【热门文章】