JavaScript Array of Key/Value Pairs Uses Literal Variable Name for Key

前端 未结 2 2007
长情又很酷
长情又很酷 2020-12-09 17:03

I\'m trying to create an array of key/value pairs by using the push method, but getting unexpected results.

console.log prints this:

<
相关标签:
2条回答
  • 2020-12-09 17:51

    Bracket notation is the correct way to use a dynamic key name:

    books[bookTitle] = author
    

    However, you need to use an intermediate object:

    var books = [];
    var bookTitle = "Tom Sawyer";
    var author = "Mark Twain";
    var foo = {};
    foo[bookTitle] = author;
    
    books.push(foo);
    
    console.log("books: %s", JSON.stringify(books))
    
    0 讨论(0)
  • 2020-12-09 18:00

    In modern Javascript (ES2015+), you can use computed properties which modifies your example code in one slight way-- square brackets are wrapped around the key name to signify it should be computed before assignment:

    var books = [];
    var bookTitle = "Tom Sawyer";
    var author = "Mark Twain";
    
    books.push({[bookTitle] : author})
    

    ... which correctly yields:

    [ { 'Tom Sawyer': 'Mark Twain' }

    This is similar to Matt Ball's original answer, but avoids the verbosity of using temporary variables.

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