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())
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM