How to fill a Javascript object literal with many static key/value pairs efficiently?

前端 未结 5 1787
-上瘾入骨i
-上瘾入骨i 2021-01-31 15:36

The typical way of creating a Javascript object is the following:

var map = new Object();
map[myKey1] = myObj1;
map[myKey2] = myObj2;

I need to

5条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 16:00

    It works fine with the object literal notation:

    var map = { key : { "aaa", "rrr" }, 
                key2: { "bbb", "ppp" } // trailing comma leads to syntax error in IE!
              }
    

    Btw, the common way to instantiate arrays

    var array = [];
    // directly with values:
    var array = [ "val1", "val2", 3 /*numbers may be unquoted*/, 5, "val5" ];
    

    and objects

    var object = {};
    

    Also you can do either:

    obj.property     // this is prefered but you can also do
    obj["property"]  // this is the way to go when you have the keyname stored in a var
    
    var key = "property";
    obj[key] // is the same like obj.property
    

提交回复
热议问题