1

I wanted to create variable name based on value sent to function in javascript. like following, when i call function variable : variable("zebra"); this should return variable name as zebra1

function create variable(i){
return i+"1";
}
var variable("zebra")="abc";//this line should create variable zebra1 and initialise as abc
user189107
  • 177
  • 2
  • 11

2 Answers2

1

Try:

window['zebra'] = 'abc';

The window object holds all the global variables, assuming this is a request for global variables.

To specifically answer your question, you could put return window[i + '1'] = 'abc'; in your variable naming function.

Alternatively, you could create a global (or local) object named variables to hold all your variables:

function whoknows() {
  var variables = {};
  variables['zebra'] = 'abc';
}

Read more on working with objects at mozilla.org

bozdoz
  • 12,550
  • 7
  • 67
  • 96
1

You can create global variable with

 window["zebra"] = "abc";

and use later ether with the same indexer syntax or directly - zebra.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179