如何判断一个变量是Array类型

2025-04-23 17:09:41

1、1.typeof操作符这种方法对于一些常用的类型来说那算是毫无压力,比如Function、String、Number、Undefined等,但是要是检测Array的对象就不起作用了。alert(typeofnull);// "object"alert(typeoffunction() {return1;});// "function"alert(typeof'梦龙小站');// "string"alert(typeof1);// "number"alert(typeofa);// "undefined"alert(typeofundefined);// "undefined"alert(typeof[]);// "object"

2、2.instanceof操作符这个操作符和JavaScript中面向对象有点关系,了解这个就先得了解JavaScript中的面向对象。因为这个操作符是检测对象的原型链是否指向构造函数的prototype对象的。var arr = [1,2,3,1];alert(arr instanceof Array); // true

3、3.对象的constructor属性除了instanceof,每个对象还有constructor的属性,利吹涡皋陕用它似乎也能进行Array的判断。vararr = [1,2,3,1];alert(arr.constructor ===Array);// true第2种和第3种方法貌似无懈可击,但是实际上还是有些漏洞的,当你在多个frame中来回穿梭的时候,这两种方法就亚历山大了。由于每个iframe都有一套自己的执行环境,跨frame实例化的对象彼此是不共享原型链的,因此导致上述检测代码失效!variframe = document.createElement('iframe');//创建iframedocument.body.appendChild(iframe);//添加到body中xArray = window.frames[window.frames.length-1].Array;vararr =newxArray(1,2,3);// 声明数组[1,2,3]alert(arrinstanceofArray);// falsealert(arr.constructor ===Array);// false

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢