Does Javascript have associative arrays?

前端 未结 6 1024
[愿得一人]
[愿得一人] 2020-12-07 02:43

Does Javascript have associative arrays? Please explain.

6条回答
  •  暖寄归人
    2020-12-07 03:27

    This answer is pretty much a copy-paste of my previous answer on this question.

    The situation has changed in the five years since this question was asked.

    Due to weak typing associative arrays can be faked in JavaScript:

    >> var names = new Array();
    undefined
    
    >> names["first"] = "Dotan";
    "Dotan"
    
    >> names["last"] = "Cohen";
    "Cohen"
    
    >> for ( key in names ) { console.log(key+" "+names[key]) }
    undefined
    first Dotan
    last Cohen
    

    That is sometimes useful, and all browsers released since 2012 support it, but there are caveats! The array cannot be simply read back:

    >> names
    Array [  ]
    

    More importantly, the array's length cannot be easily retrieved:

    >> names.length
    0
    

    Therefore this is not an associative array in the sense that JavaScript would have supported it had it been intended, but rather a workaround that is often useful if for whatever reason a real JS object does not support what you need:

    >> var names = {};
    undefined
    
    >> names.first = "Dotan";
    "Dotan"
    
    >> names.last = "Cohen";
    "Cohen"
    
    >> for ( key in names ) { console.log(key+" "+names[key]) }
    undefined
    first Dotan
    last Cohen
    
    >> names
    Object { first: "Dotan", last: "Cohen" }
    
    >> Object.keys(names).length
    2
    

提交回复
热议问题