简体   繁体   English

如何将变量值用于另一个对象的键?

[英]How to use a variable value for the key of another object?

I have something like : 我有类似的东西:

var myMenu= [
  {
    'My English Title':function(menuItem,menu) 
                       { ... }
  }];

Now, I want the replace 'My English Title' by an other JSON structure value LOC.MENU_TITLE . 现在,我希望用其他JSON结构值LOC.MENU_TITLE替换“我的英文标题”。

I have try: 我试过了:

var myMenu= [
  {
    LOC.MENU_TITLE:function(menuItem,menu) 
                       { ... }
  }];

But it doesn't work. 但它不起作用。 Any one can give me an hint of how to get JSON value inside a JSON variable? 任何人都可以给我一个如何在JSON变量中获取JSON值的提示?

Edit: This is to use the Context Menu of Jquery but I got a problem with all solutions below and it's when it's time to pass the String for the Separator. 编辑:这是使用Jquery上下文菜单,但我遇到了下面所有解决方案的问题,而且是时候传递分隔符的字符串了。 It doesn't show the separator because it pass the string into an object instead of just the string. 它不显示分隔符,因为它将字符串传递给对象而不是字符串。

Example: 例:

var menu1 = [
  {'Option 1':function(menuItem,menu) { alert("You clicked Option 1!"); } },
  $.contextMenu.separator,
  {'Option 2':function(menuItem,menu) { alert("You clicked Option 2!"); } }
];
var tempElement = {};
tempElement[ LOC.MENU_TITLE ] = function(menuItem, menu) {};

myMenu = [ tempElement ];

Addressing your edit. 解决您的编辑问题。 Try the following 请尝试以下方法

var myMenu = [ {}, $.contextMenu.separator, {} ];

myMenu[0][ LOC.MENU_TITLE ]  = function(menuItem, menu) {};
myMenu[2][ LOC.MENU_TITLE2 ] = function(menuItem, menu) {};

JavaScript object literals expect the keys to be either an Identifier , a String literal or a Number literal, a workaround can be to build your object step by step, using the bracket notation: JavaScript 对象文字要求键可以是IdentifierString文字或Number文字,解决方法可以是使用括号表示法逐步构建对象:

var myMenu= [{}];
myMenu[0][LOC.MENU_TITLE] = function(menuItem,menu){ /*...*/ };

Note that the above isn't JSON. 请注意,上面不是JSON。

JSON is a language-agnostic data interchange format, its grammar differs from the JavaScript Object literals, basically by allowing only string keys and the values must be an object, array, number, string, or the literal names: false , null true . JSON是一种与语言无关的数据交换格式,其语法与JavaScript Object文字不同,基本上只允许字符串键,值必须是对象,数组,数字,字符串或文字名称: falsenull true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM