Javascript: Server sided dynamic variable names

旧城冷巷雨未停 提交于 2019-12-23 07:20:09

问题


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.


回答1:


Generally you would do something like:

var myVariables = {};
var variableName = 'foo';

myVariables[variableName] = 42;
myVariables.foo // = 42



回答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]);


来源:https://stackoverflow.com/questions/12593101/javascript-server-sided-dynamic-variable-names

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