Javascript:服务器端动态变量名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12593101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:36:46  来源:igfitidea点击:

Javascript: Server sided dynamic variable names

javascriptnode.jsdynamic-variables

提问by hexacyanide

How would I create dynamic variable names in NodeJS? Some examples say to store in the windowvariable, but I was assuming that is client-side Javascript. Correct me if I'm wrong.

如何在 NodeJS 中创建动态变量名?一些示例说要存储在window变量中,但我假设那是客户端 Javascript。如我错了请纠正我。

回答by Bill

Generally you would do something like:

通常,您会执行以下操作:

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

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

回答by Mahn

In node.js there is the globalcontext, which is the equivalent of the windowcontext 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.

在 node.js 中有global上下文,它相当于window客户端 js中的上下文。在任何闭包/函数/模块之外声明一个变量,就像在普通 Javascript 中一样,将使其驻留在全局上下文中,即作为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:

这在 node.js 中会变成:

var something = 42;
var varname = "something";
console.log(global[varname]);

回答by Raj Kumar

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);