JavaScript set object key by variable

This question already has an answer here:

  • How to use a variable for a key in a JavaScript object literal? 7 answers

  • 您需要先创建对象,然后使用[]进行设置。

    var key = "happyCount";
    var obj = {};
    obj[key] = someValueArray;
    myArray.push(obj);
    

    Try something like this

    var yourObject = {};
    
    yourObject[yourKey] = "yourValue";
    
    console.log(yourObject );
    

    example:

    var person = {};
    var key = "name";
    
    person[key] /* this is same as person.name */ = "John";
    
    console.log(person); // should print  Object { name="John"}
    

        var person = {};
        var key = "name";
        
        person[key] /* this is same as person.name */ = "John";
        
        console.log(person); // should print  Object { name="John"}
    链接地址: http://www.djcxy.com/p/27232.html

    上一篇: JavaScript中[[Prototype]]和原型之间的关系

    下一篇: JavaScript通过变量设置对象关键字