JavaScript 通过变量关联数组
我想将一个变量传递到我的 monthHash
变量的键中:
var monthHash = new Array();
monthHash["JAN"] = "Jan";
monthHash["FEB"] = "Feb";
...
monthHash["NOV"] = "Nov";
monthHash["DEV"] = "Dec";
这样我就可以这样做:
alert(monthHash[the_variable]);
而不是使用 switch case 来完成此操作。
然而,当我尝试时,我收到错误。有没有办法让变量指示 JavaScript 中键的字符串标识符?
I'd like to pass a variable into the key of my monthHash
variable here:
var monthHash = new Array();
monthHash["JAN"] = "Jan";
monthHash["FEB"] = "Feb";
...
monthHash["NOV"] = "Nov";
monthHash["DEV"] = "Dec";
Such that I can do this:
alert(monthHash[the_variable]);
Instead of using a switch case to go through this.
When I try, however, I get an error. Is there a way I can have a variable indicate a string identifier for the key in JavaScript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我可以看到您的代码可能生成错误的唯一情况是当
the_variable
未定义时(您将收到ReferenceError
)。但是,
Array
并不意味着用于键/值对。你应该使用一个对象来代替:The only case that I can see where your code can generate an error is when
the_variable
is undefined (where you would receive aReferenceError
).However,
Array
is not meant to be used for key/value pairs. You should use an object instead:将其声明为一个对象:
或
Declare it to be an object:
or