JavaScript 通过变量关联数组

发布于 2024-09-06 19:11:09 字数 390 浏览 1 评论 0原文

我想将一个变量传递到我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凉栀 2024-09-13 19:11:09

我可以看到您的代码可能生成错误的唯一情况是当 the_variable 未定义时(您将收到 ReferenceError)。

但是,Array 并不意味着用于键/值对。你应该使用一个对象来代替:

var monthHash = {};
monthHash['JAN'] = 'Jan';
monthHash['FEB'] = 'Feb';
monthHash['NOV'] = 'Nov';
monthHash['DEC'] = 'Dec';

var the_variable = 'NOV';

alert(monthHash[the_variable]);  // alerts 'Nov'

The only case that I can see where your code can generate an error is when the_variable is undefined (where you would receive a ReferenceError).

However, Array is not meant to be used for key/value pairs. You should use an object instead:

var monthHash = {};
monthHash['JAN'] = 'Jan';
monthHash['FEB'] = 'Feb';
monthHash['NOV'] = 'Nov';
monthHash['DEC'] = 'Dec';

var the_variable = 'NOV';

alert(monthHash[the_variable]);  // alerts 'Nov'
握住我的手 2024-09-13 19:11:09

将其声明为一个对象:

var monthHash = {};
monthHash["JAN"] = ..;

var monthHash = {jan: "...", ...}

var x = "jan";
alert(monthHash[x]);

Declare it to be an object:

var monthHash = {};
monthHash["JAN"] = ..;

or

var monthHash = {jan: "...", ...}

var x = "jan";
alert(monthHash[x]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文