Is it possible to add dynamically named properties to JavaScript object?

后端 未结 19 1551
攒了一身酷
攒了一身酷 2020-11-21 05:39

In JavaScript, I\'ve created an object like so:

var data = {
    \'PropertyA\': 1,
    \'PropertyB\': 2,
    \'PropertyC\': 3
};

Is it poss

19条回答
  •  面向向阳花
    2020-11-21 06:18

    in addition to all the previous answers, and in case you're wondering how we're going to write dynamic property names in the Future using Computed Property Names ( ECMAScript 6 ), here's how:

    var person = "John Doe";
    var personId = "person_" + new Date().getTime();
    var personIndex = {
        [ personId ]: person
    //  ^ computed property name
    };
    
    personIndex[ personId ]; // "John Doe"
    

    reference: Understanding ECMAScript 6 - Nickolas Zakas

提交回复
热议问题