How to create an associative array in JavaScript literal notation

前端 未结 6 758
再見小時候
再見小時候 2021-01-30 16:39

I understand that there are no associative arrays in JavaScript, only objects.

However I can create an array with string keys using bracket

相关标签:
6条回答
  • 2021-01-30 17:15

    Arrays and Objects are different things.

    For an object, you can do things like:

    var obj = { "property1": "value1" };
    obj.property2 = "value2";
    

    For arrays, you have to do this:

    var arr = [];
    arr[0] = "value";
    
    0 讨论(0)
  • 2021-01-30 17:18

    JavaScript has no associative arrays, just objects. Even JavaScript arrays are basically just objects, just with the special thing that the property names are numbers (0,1,...).

    So look at your code first:

    var myArray = []; // Creating a new array object
    myArray['a'] = 200; // Setting the attribute a to 200
    myArray['b'] = 300; // Setting the attribute b to 300
    

    It's important to understand that myArray['a'] = 200; is identical to myArray.a = 200;!

    So to start with what you want: You can't create a JavaScript array and pass no number attributes to it in one statement.

    But this is probably not what you need! Probably you just need a JavaScript object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. And that can be done easily:

    var myObj = {a: 200, b: 300};
    

    But it's important to understand that this differs slightly from what you did. myObj instanceof Array will return false, because myObj is not an ancestor from Array in the prototype chain.

    0 讨论(0)
  • 2021-01-30 17:20

    You want to use an object in this case

    var myObject = {'a' : 200, 'b' : 300 };
    

    This answer links to a more in-depth explanation: How to do associative array/hashing in JavaScript

    0 讨论(0)
  • 2021-01-30 17:27

    You can do what you wanted to do this way:

    myNewArray = new Array ({'a' : 200, 'b' : 300})
    
    0 讨论(0)
  • 2021-01-30 17:29

    You can use Map:

    var arr = new Map([
       ['key1', 'User'],
       ['key2', 'Guest'],
       ['key3', 'Admin'],
    ]);
    
    var res = arr.get('key2');
    console.log(res); // The value is 'Guest'
    
    0 讨论(0)
  • 2021-01-30 17:36

    Well, you are creating an array, which is in fact an object:

    var arr = [];
    arr.map;
    // function(..)
    arr['map'];
    // function(..)
    
    arr['a'] = 5;
    
    console.log(arr instanceof Object); // true
    

    You can add fields and functions to arr. It does not "insert" them into the array though (like arr.push(...)).

    You can refer to an object fields with the [] syntax.

    0 讨论(0)
提交回复
热议问题