如何判断一个js对象是不是Array

JavaScript020

如何判断一个js对象是不是Array,第1张

1、每一数据类型均可判断出来的方法Object.prototype.toString.call()

var a = [1,3,4,6]

Object.prototype.toString.call(a) // "[object Array]"

var a = 'sdfasf'

Object.prototype.toString.call(a) // "[object String]"

var a = {a: 324}

Object.prototype.toString.call(a) // "[object Object]"

var a = true

Object.prototype.toString.call(a) // "[object Boolean]"

var a = null

Object.prototype.toString.call(a) // "[object Null]"

var a = undefined

Object.prototype.toString.call(a) // "[object Undefined]"

var a = function() {}

Object.prototype.toString.call(a) // "[object Function]"

2、使用typeof判断数据类型的缺点:

typeof针对数组、对象以及null判断出来的数据类型均为object

$.isArray([1,2])              // 数组

$.isFunction(function () { }) // 函数function

$.isEmptyObject(null)         // null,undefind

$.isXMLDoc()    // xml

typeof (2) === "number"    // 数字

typeof ("2") === "string"  // 字符串

typeof (true) === "boolean"// bool型

typeof (function () { }) === "function"// 函数function

js判断数组为空的方法有以下几种:

1、利用数组的length属性来判断

if(arrayName.length >0){

//数组不为空

}else{

//数组为空

}

2、利用先判断类型,再判断长度的方法来实现

if(A &&A.constructor==Array &&A.length==0)

这样增加了代码的安全性,因为不是Array类型的话是没有length属性的。