0

In config.txt, I have the following strings:

Dispatcher=argo
Address=10.5.23.14
User=joe

In my script.js, I have the variables:

var Dispatcher, Address, User;

In script.js, I read config.txt, parse strings and get name/value pairs:

ConfigPair = ConfigString.split("=");
VarName = ConfigPair[0];
VarValue = ConfigPair[1];

What I want is to assign VarValue to the VarName variable. Say, if I get "Address" in VarName and "10.5.23.14" in VarValue, I want to set Address variable to 10.5.23.14.

I don't want to do something like that:

if (VarName == "Dispatcher") {
    Dispatcher = VarValue;
} else if (VarName == "Address") {
    Address = VarValue;
} else if bla-bla-bla

I want to somehow "read" the value of VarName and assign VarValue to the corresponding variable. Is it possible to do it in Windows Script Host (JScript)? I played with eval, but failed to make it work. Any ideas?

Thanks, Racoon

Racoon
  • 951
  • 3
  • 14
  • 32

3 Answers3

2

If you work in a browser you can use the global window object like so :

// VarName = "User"
// VarValue = "joe"
window[VarName] = VarValue;
alert(User); // prints "joe"
User = 'jack';
alert(User); // prints "jack"

Edit

Tested with WSH and Windows 7 :

(function () {
    var VarName = 'User'; // ConfigPair[0]
    var VarValue = 'joe'; // ConfigPair[1]
    this[VarName] = VarValue;
})();
WSH.Echo(User); // prints "joe"
WSH.Quit();
  • Thanks! But I'm not in the browser. Windows Script Host, running cscript script.js from command line. – Racoon Mar 02 '13 at 09:30
  • I have found a [similar question](http://stackoverflow.com/questions/9642491/getting-a-reference-to-the-global-object-in-an-unknown-environment-in-strict-mod) telling that you can access the global object like so : `var GLOBAL = (function(){return this}());` –  Mar 02 '13 at 09:39
1

You can create an object and assign properties dynamically,

var VarHolder = {};

VarHolder[VarName] = VarValue;
Jodes
  • 14,118
  • 26
  • 97
  • 156
  • Thanks, very useful. That being said, no way to directly assign to the variable, correct? I want to redefine variable in the script if there is a corresponding string in the config. With your solution I can do this: var Dispatcher="disp1"; if VarHolder["Dispatcher"] {Dispatcher=VarHolder["Dispatcher"]. it is OK, but isn't there more compact/simple way? – Racoon Mar 02 '13 at 08:00
1

If I get the question right, then this topic may help.

(function() { eval.apply(this, arguments); }("x=1;y=2"));
WScript.Echo("x=" + x, "y=" + y); // x=1 y=2
Community
  • 1
  • 1
Panayot Karabakalov
  • 3,109
  • 3
  • 19
  • 28