在 CoffeeScript 中,如何使用变量作为哈希中的键?
例如:
所以:
foo = "asdf"
{foo: "bar"}
eval foo
# how do I get {"asdf": "bar"} ?
# this will throw parse error:
{(eval foo): "bar"}
这是一个简单的语法问题:如何让 CoffeeScript 动态构造哈希,而不是手工完成?
eg:
So:
foo = "asdf"
{foo: "bar"}
eval foo
# how do I get {"asdf": "bar"} ?
# this will throw parse error:
{(eval foo): "bar"}
This is a simple syntax question: how do I get CoffeeScript to construct a hash dynamically, rather than doing it by hand?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
CoffeeScript 与 JavaScript 一样,不允许您使用表达式/变量作为对象文本中的键。这是短暂的支持,但在 0.9.6 版本中被删除。创建对象后需要设置属性。
CoffeeScript, like JavaScript, does not let you use expressions/variables as keys in object literals. This was support briefly, but was removed in version 0.9.6. You need to set the property after creating the object.
虽然有点丑,但仍然是一句台词(抱歉迟到了):
{ "#{foo}": bar }
Somewhat ugly but a one-liner nonetheless (sorry for being late):
{ "#{foo}": bar }
如果您希望使用 Coffeescript 的最小语法来定义关联数组,我建议您创建一个简单的两行方法,在定义数组后将
变量名称
键转换为变量值。我是这样做的(实际数组要大得多):
SampleEvents
数组现在是:If you're looking to use Coffeescript's minimal syntax for defining your associative array, I suggest creating a simple two line method to convert the
variable name
keys into the variable values after you've defined the array.Here's how I do it (real array is much larger):
The
SampleEvents
array is now:试试这个:
Try this:
对于将来发现这个问题的任何人,从 CoffeeScript 1.9.1 开始,支持内插对象文字键!
语法如下所示:
请参阅 https://github.com/jashkenas/coffeescript/commit/76c076db555c9ac7c325c3b285cd74644a9bf0d2
For anyone that finds this question in the future, as of CoffeeScript 1.9.1 interpolated object literal keys are supported!
The syntax looks like this:
See https://github.com/jashkenas/coffeescript/commit/76c076db555c9ac7c325c3b285cd74644a9bf0d2
你为什么要使用
eval
?您可以按照与 JavaScript 中完全相同的方式进行操作:翻译为 JavaScript:
结果是
h
看起来像{'asdf': 'bar'}< /代码>。
Why are you using
eval
at all? You can do it exactly the same way you'd do it in JavaScript:That translates to this JavaScript:
And the result is that
h
looks like{'asdf': 'bar'}
.