笔记-数组类型

来源:互联网 发布:计算机病毒 知乎 编辑:程序博客网 时间:2024/06/05 05:37

       给定一个对象,判定其是否为数组是非常有用的,在ECMASript5中,可以使用Array.isArray()来做此事:

Array.isArray([]); //trueArray.isArray({}); //false

        但是在ECMAScript5之前,要区分数组和非数组是非常困难的,typeof用于数组结果是对象 object,使用instanceof操作符看下结果:

[] instanceof Array //true;({}) instanceof Array //false;

        貌似可以解决此问题,但是使用操作符instanceof的问题是Web浏览器中可能有多个窗口或窗体存在。每个窗口都有自己的javascript运行环境,有自己的全局对象。并且,每个全局对象都有一组自己的构造函数。因此一个窗体中的对象不可能是另外一个窗体中的构造函数实例。这也说明操作符instanceof不是可靠的数组检测方法。

       解决方法是检测对象的类属性,对数组而言,该属性是Array,在ECMAScript3中这段函数可以这么写:

var isArray = Function.isArray || function(o) {return typeof o === 'object' &&Ojbect.prototype.toString.call(o) === '[object Array]';}

其实上述代码也是ECMAScript5中 Array.isArray()所做的事情。

看到这段话,我突然想起Jquery源码关于isArray的表述:

isArray: Array.isArray || function( obj ) {return jQuery.type(obj) === "array";},

 

type: function( obj ) {return obj == null ?String( obj ) :class2type[ core_toString.call(obj) ] || "object";},
core_toString = Object.prototype.toString,
// Populate the class2type mapjQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {class2type[ "[object " + name + "]" ] = name.toLowerCase();});

当我们看到这些代码时,是不是觉得就是刚才所描述那样实现的呢。

原创粉丝点击