JavaScript通过变量设置对象关键字

这个问题在这里已经有了答案:

  • 如何在JavaScript对象文字中为键使用变量? 7个答案

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

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

    尝试这样的事情

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

    例:

    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/27231.html

    上一篇: JavaScript set object key by variable

    下一篇: How can I add a key/value pair to a JavaScript object?