Javascript: Server sided dynamic variable names
17,350
Solution 1
Generally you would do something like:
var myVariables = {};
var variableName = 'foo';
myVariables[variableName] = 42;
myVariables.foo // = 42
Solution 2
In node.js there is the global
context, which is the equivalent of the window
context in client-side js. Declaring a variable outside of any closure/function/module as you would in plain Javascript will make it reside in the global context, that is, as a property of global
.
I understand from your question that you want something akin to the following:
var something = 42;
var varname = "something";
console.log(window[varname]);
This in node.js would become:
var something = 42;
var varname = "something";
console.log(global[varname]);
Solution 3
Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.
var type = 'article';
this[type+'_count'] = 1000; // in a function we use "this";
alert(article_count);
Related videos on Youtube
Comments
-
hexacyanide over 1 year
How would I create dynamic variable names in NodeJS? Some examples say to store in the
window
variable, but I was assuming that is client-side Javascript. Correct me if I'm wrong. -
Bill over 11 yearsI know this is what he was hinting at in the question, but putting things in the
global
namespace is frowned upon innode
. You won't find many libraries that do this kind of thing. -
Mahn over 11 years@Bill correct, but I was under the impression OP was confused at the lack of the window context in node.js and would like to know an equivalent.
-
jonathanKingston over 11 yearsPerhaps using "runInThisContext" with the vm module in node would be slightly preferred? davidmclifton.com/2011/08/18/node-js-virtual-machine-vm-usage
-
andcl almost 5 yearsWrapping variable names into a standard object. Yes, very smart and clever :)
-
Nathan Boaldin almost 4 years