如何判断一个对象为数组

1.用Array对象isArray方法来判断

不得不承认这是一个超级简单又好用的方法,参数是数组时返回true,不是数组时则返回false

var a=[];
Array.isArray(a)    //返回true

var b='hello world';
Array.isArray(b)       //返回false

2.用instanceof判断

var a=[];
console.log(a instanceof Array)   //返回true

console.log(a instanceof Object)    //同样也返回true

使用instanceof来判断存在一个问题,因为数组也是对象,所以,如果判断是否为数组时应当用Array来判断

3.判断是否存在数组上的方法,比如push,splice,length等

var a=[];
a.push('e');       //返回1

var b={};
console.log(b.push('e'))     // 报错:b.push is not a function

4.用toString方法,这个方法可以判断所有类型,麻烦但是很通用

可以判断的类型包括:String、Number、Boolean、Undefined、Null、Function、Date、Array、RegExp、Error、HTMLDocument 等, 基本上,所有的数据类型都可以通过这个方法获取到。

function isType(data,type) {
    return Object.prototype.toString.call(data) === "[object "+type+"]";
}   

注意的问题:必须通过 call 或 apply 来调用,而不能直接调用 toString !!!!
从原型链的角度讲,所有对象的原型链最终都指向了 Object, 按照JS变量查找规则,其他对象应该也可以直接访问到 Object 的 toString方法,而事实上,大部分的对象都实现了自身的 toString 方法,这样就可能会导致 Object 的 toString 被终止查找,因此要用 call或apply 来强制调用Object 的 toString 方法。

5.constructor方法

var a=[];
a.constructor==Array;     //返回true

通用的判断方法

function isArray(object) {
return object && typeof object === 'object' && Array == object.constructor;
}

6.jquery.type() 这是jquery当中的方法

  • 1.如果对象是undefined或null,则返回相应的“undefined”或“null”。
  • 2.如果对象有一个内部的[[Class]]和一个浏览器的内置对象的 [[Class]] 相同,我们返回相应的 [[Class]] 名字
  • 3.其他一切都将返回它的类型“object”。
jQuery.type( [] ) === "array"
jQuery.type( undefined ) === "undefined"
jQuery.type() === "undefined"
jQuery.type( window.notDefined ) === "undefined"
jQuery.type( null ) === "null"
jQuery.type( true ) === "boolean"
jQuery.type( 3 ) === "number"
jQuery.type( "test" ) === "string"
jQuery.type( function(){} ) === "function"
jQuery.type( new Date() ) === "date"
jQuery.type( /test/ ) === "regexp"

猜你喜欢

转载自blog.csdn.net/github_39406334/article/details/78121965