js里判断变量是数组还是对象的四种方法

JavaScript022

js里判断变量是数组还是对象的四种方法,第1张

因为无论是数组还是对象,对于typeof的操作返回值都为object,所以就有了区分数组类型和对象类型的需要:

方一:通过length属性:一般情况下对象没有length属性值,其值为undefiend,而数组的length值为number类型

缺点:非常不实用,当对象的属性存在length,且其值为number(比如类数组),则该方法失效,不建议使用,看看即可。

*方二:通过instanceof来判断区分

var arr = [1, 2, 3] var obj = {name: 'lyl',age: 18,1: 'name'}console.log(arr instanceof Array)//trueconsole.log(obj instanceof Array)//false

*方三:通过constructor

var arr = [1, 2, 3] var obj = {name: 'lyl',age: 18,1: 'name'}console.log(arr.constructor === Array)//trueconsole.log(obj.constructor === Array)//false

比如有一个变量a,

var a = xxxxxxxx

if(typeof a == "number") {

    //a是数

} else if(typeof a == "string") {

    //a是字符串

} else if(typeof a == "undefined") {

    //a是未定义

} else if(typeof a == "boolean") {

    //a是bool变量

} else if(typeof a == "object") {

    //a是对象

}

或者使用instance of:

var b = new Date()

if(b instanceof Date) {

    //b是Date类型的

}

var c = []

if(c instanceof Array) {

    //c是数组

}