JavaScript判断是否是数组

在 ECMAScript5中定义了一个新的方法Array.isArray(). 如果参数是数组的话,就返回true

eg:

Array.isArray([]); // true

如果里面换一个类似数组的对象字面量(object literal)呢

Array.isArray({
       name: "Luke",
       "0": 1,
        test: function() {}
});   // false

但是如果你的开发环境不支持ECMAScript5, 也就是说你没法使用Array.isArray()方法,你又该怎么做呢

这时,你可以通过Object.prototype.toString()方法来代替, 调用Object.prototype.toString.call()方法,并传入数组对象,将返回字符串"[object Array]". 如果传入的是对象上下文,那么返回的字符串则是"[object Object]"

所以,如果Array.isArray 不顶用,我们可以重写方法如下,假如要判断的数组对象为testArgs

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

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

     };
}

 

posted on 2019-03-12 13:02  新西兰程序员  阅读(261)  评论(0编辑  收藏  举报