Best way to store a key=>value array in JavaScript?

前端 未结 7 1897
借酒劲吻你
借酒劲吻你 2020-11-28 00:27

What\'s the best way to store a key=>value array in javascript, and how can that be looped through?

The key of each element should be a tag, such as

7条回答
  •  感动是毒
    2020-11-28 01:22

    That's just what a JavaScript object is:

    var myArray = {id1: 100, id2: 200, "tag with spaces": 300};
    myArray.id3 = 400;
    myArray["id4"] = 500;
    

    You can loop through it using for..in loop:

    for (var key in myArray) {
      console.log("key " + key + " has value " + myArray[key]);
    }
    

    See also: Working with objects (MDN).

    In ECMAScript6 there is also Map (see the browser compatibility table there):

    • An Object has a prototype, so there are default keys in the map. This could be bypassed by using map = Object.create(null) since ES5, but was seldomly done.

    • The keys of an Object are Strings and Symbols, where they can be any value for a Map.

    • You can get the size of a Map easily while you have to manually keep track of size for an Object.

提交回复
热议问题