Dynamic variable names in Javascript

为君一笑 提交于 2019-12-01 10:16:22

问题


I use jQuery Impromptu prompts in my application and they're very helpful.

However to call the Impromptu prompts you need to specify the button names and their return values like so:

$.prompt('Example 2',{ buttons: { Ok: true, Cancel: false } });

I would really like to have dynamic button names, something like this:

function showprompt(question, button1, button2) {
  $.prompt(question,{ buttons: { button1: true, button2: false } });
}

But this doesn't seem to work, the buttons are just called 'button1' and 'button2'!

I've tried using eval(button1) and ''+button1 but they bring up syntax errors.

Any suggestions?


回答1:


Since property names in an object literal can be identifiers (rather than strings), you can't use a variable for them.

You have to create the object, and then use square bracket notation to assign the values.

function showprompt(question, button1, button2) {
  var buttons = { };
  buttons[button1] = true;
  buttons[button2] = false;
  $.prompt(question,{ buttons: buttons });
}


来源:https://stackoverflow.com/questions/6609091/dynamic-variable-names-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!