Javascript:变量作为数组键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12244483/
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-08-23 07:30:21  来源:igfitidea点击:

Javascript: variable as array key

javascriptarrays

提问by Barta Tamás

I im building and array where my array key is from a variable like this:

我正在构建和数组,其中我的数组键来自这样的变量:

var art = $('#article_id').val();
var stk =  $('#stk').val();
elements ={ art : stk };
alert(elements[art]);

but i end up with this output art=>50instead of 5123=>50

但我最终得到了这个输出art=>50而不是5123=>50

回答by Jon

ECMAScript 2015 (aka ES6 Harmony)

ECMAScript 2015(又名 ES6 Harmony)

ES 2015 provides support for this through a feature called computed property names(although the relevant section of the specis called "Object Initializer").

ES 2015 通过一个称为计算属性名称的特性(尽管规范的相关部分称为“对象初始值设定项”)为此提供支持。

Simply put, surround the variable (in general, any expression) with square brackets to evaluate it and use the result as a property name. In your example that would be

简单地说,用方括号将变量(通常是任何表达式)括起来以对其进行评估并将结果用作属性名称。在你的例子中,这将是

elements = { [art]: stk };

Original answer (targeting ES5)

原始答案(针对 ES5)

You cannot create object literals like that. You need to write

你不能像那样创建对象文字。你需要写

elements = {};
elements[art] = stk;

The reason why elements = { art: stk }does not work is because it is equivalent to elements = { "art": stk }(with quotes). The two versions are equivalent in JavaScript as long as artis a legal identifier, and the second version makes it clear what's going on.

之所以elements = { art: stk }不起作用,是因为它相当于elements = { "art": stk }(带引号)。只要art是合法标识符,这两个版本在 JavaScript 中是等效的,第二个版本清楚地说明了发生了什么。

回答by xdazz

Use below to add dynamic key to an object.

使用下面将动态键添加到对象。

elements = {};
elements[art] = stk;