js 区分 数组和字典


a = {"key0": [1,2,3,4]};
console.log(a.length);
console.log(a.key0.length);

>>> undefined
>>> 4 

字典没有 长度, 数组有长度.

if (a.length==undefined){
    console.log("a为字典")
}
else if (a.key0.length > 0){
    console.log("a.key0的值为数组")
    
}

a = "123"

辨别对象是字符串

typeof a => string

辨别对象是 数组的三个方法

Array.isArray(x)
x.constructor.toString().indexOf("Array") > -1
x instanceof Array

识别对象类型

x = [1,2,3]
if (x.constructor.toString().indexOf("Array")>-1)
{
    alert("对象为数组")
}
elif (x.constructor.toString().indexOf("Number")>-1)
{
    alert("对象为数字")
}
elif (x.constructor.toString().indexOf("String")>-1)
{
    alert("对象为字符")
}
elif (x.constructor.toString().indexOf("Object")>-1)
{
     alert("对象为字典")
}
else
{
    alert(x.constructor.toString())
}

posted on 2019-07-03 09:57  游荡的鱼  阅读(1902)  评论(0编辑  收藏  举报

导航