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