JS怎么判断数组类型?

1.判断对象的constructor是否指向Array,接着判断特殊的属性length,splice等。[应用的是constructor的定义:返回对象所对应的构造函数。]

eg: [].constructor == Array; //true

2.使用instanceof 判断对象是否是数组的实例,[应用的是instanceof的定义:某实例是否是某构造函数的实例],[极端情况下不行,比如iframe的嵌套页面之间的判断],[Array实质上是window.Array]

eg: var arr = []; console.log(arr instanceof Array); //返回true。

3.[最优方式]使用Object.prototype.toString().call(arr) === "[object Array]"

4.ES5中定义了Array.isArray(arr)方法,返回true/false。

对于不兼容isArray()方法的,可以用下面这个代码:

if(typeof Array.isArray === "undefined"){

    Array.isArray = function(arg){

        return Object.prototype.toString.call(arg) === "[object Array]";

    };

}

参考链接:https://www.cnblogs.com/linda586586/p/4227146.html

               https://blog.csdn.net/u010297791/article/details/55049619


posted @ 2018-08-12 12:26  惊沙男孩  阅读(1298)  评论(0编辑  收藏  举报