键/值对的 JavaScript 数组使用文字变量名作为键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18491828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:08:40  来源:igfitidea点击:

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

javascript

提问by Raj

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

我正在尝试使用该push方法创建一个键/值对数组,但得到了意想不到的结果。

console.logprints this:

console.log打印这个:

books: [{"bookTitle":"Mark Twain"}]

书籍:[{"bookTitle":"马克吐温"}]

Whereas I would expect this:

而我希望这样:

books: [{"Tom Sawyer" : "Mark Twain"}]

书籍:[{“汤姆索亚”:“马克吐温”}]

Here's the code:

这是代码:

var books = [];
var bookTitle = "Tom Sawyer";
var author = "Mark Twain";

books.push({bookTitle : author})

console.log("books: %s", JSON.stringify(books))

I've tried books.bookTitle = authorand books[bookTitle] = author, but the result is the same. Any help is appreciated.

我试过books.bookTitle = authorand books[bookTitle] = author,但结果是一样的。任何帮助表示赞赏。

回答by Matt Ball

Bracket notationis 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))

回答by Lee Benson

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

在现代 Javascript (ES2015+) 中,您可以使用计算属性以一种轻微的方式修改您的示例代码——方括号括在键名周围以表示它应该赋值之前计算:

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.

这类似于 Matt Ball 的原始答案,但避免了使用临时变量的冗长。