Javascript:变量作为数组键 [英] Javascript: variable as array key
问题描述
我正在构建和数组,其中我的数组键来自这样的变量:
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]);
但我最终得到这个输出 art=>50
而不是 5123=>50
but i end up with this output art=>50
instead of 5123=>50
推荐答案
ECMAScript 2015(又名 ES6 Harmony)
ES 2015 通过名为计算属性名称的功能为此提供支持(尽管相关的
ECMAScript 2015 (aka ES6 Harmony)
ES 2015 provides support for this through a feature called computed property names (although the relevant section of the spec is called "Object Initializer").
简单地说,用方括号将变量(通常是任何表达式)括起来以对其进行评估并将结果用作属性名称.在你的例子中,这将是
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 };
原始答案(针对 ES5)
你不能像那样创建对象字面量.你需要写
Original answer (targeting ES5)
You cannot create object literals like that. You need to write
elements = {};
elements[art] = stk;
elements = { art: stk }
之所以不起作用,是因为它等价于elements = { "art": stk }
(带引号).只要 art
是合法标识符,这两个版本在 JavaScript 中是等效的,第二个版本清楚地说明了发生了什么.
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 art
is a legal identifier, and the second version makes it clear what's going on.
这篇关于Javascript:变量作为数组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!