-2

I need to call a variable from within a variable.

I have a variable called vmX_cores. I need to loop through the vms I have and call that variable dynamically.

var vms = ["vm1", "vm2", "vm3"];
var totalVms = vms.length;

var vm1_cores = 2;
var vm2_cores = 4;
var vm3_cores = 8;

function ifScript() {
   if (totalVms == 0) {
      return 'done';
   } else {
      var curVM = vms[totalVms - 1];
      var variableToUse = curVM + '_cores';
      totalVms--;
      return 'notDone';
   }
}

When I call variableToUse this returns "vmX_cores" but I need it to return the number not a string.

huan0602
  • 13
  • 2

2 Answers2

0

You can use window[vmX_cores] to get the value of that variable string.

eg : var x = window["vm1_cores"]

In your case :

var x = window[variableToUse]

Munawir
  • 3,346
  • 9
  • 33
  • 51
0

A global variable is accessible as a property of the global object, which is window for a browser and global for node. See Getting a reference to the global object in an unknown environment in strict mode

Since you have the name of the variable/property, you can use bracket access.

// This code works in ES3, ES5 and strict mode to get the global object
var globalObj = (function(){ return this || (1,eval)('this') })();
var variableToUse = curVM + '_cores';
var actualValue = globalObj[variableToUse]; 
Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • I thought this was going to work but I got: WrappedException of "window" is not defined – huan0602 Feb 24 '16 at 03:16
  • Did you even look at the link I posted in my answer? You can use `global` in node, but the link tells you a better way – Ruan Mendes Feb 24 '16 at 14:10
  • That worked! Thank you! I did as `var global = (eval)(variableToUse);` then called global and I got the right number – huan0602 Feb 24 '16 at 14:58
  • @huan0602 That is not what that post was saying, you are using `eval` to evaluate the variable name, which is usually frowned upon. In this case, there's no problem because all the variables being `evaled` are under your control. I've updated my answer with the correct answer that works under node and the browser. – Ruan Mendes Feb 25 '16 at 13:34