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

后端 未结 2 1813
灰色年华
灰色年华 2020-12-06 11:48

I have something like :

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

Now, I wan

相关标签:
2条回答
  • 2020-12-06 11:59
    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) {};
    
    0 讨论(0)
  • 2020-12-06 12:02

    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:

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

    Note that the above isn't 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.

    0 讨论(0)
提交回复
热议问题