如何在 NodeJS 中创建动态变量名?一些例子说存储在window
变量中,但我假设那是客户端 Javascript。如我错了请纠正我。
问问题
17425 次
4 回答
24
通常,您会执行以下操作:
var myVariables = {};
var variableName = 'foo';
myVariables[variableName] = 42;
myVariables.foo // = 42
于 2012-09-26T01:08:54.990 回答
9
在 node.js 中有global
上下文,它相当于window
客户端 js 中的上下文。像在普通 Javascript 中那样在任何闭包/函数/模块之外声明一个变量将使它驻留在全局上下文中,即作为global
.
我从您的问题中了解到,您想要类似于以下内容:
var something = 42;
var varname = "something";
console.log(window[varname]);
这在 node.js 中会变成:
var something = 42;
var varname = "something";
console.log(global[varname]);
于 2012-09-26T01:07:08.783 回答
1
只是不知道一个糟糕的答案会得到这么多票。这是很容易的答案,但你让它变得复杂。
var type = 'article';
this[type+'_count'] = 1000; // in a function we use "this";
alert(article_count);
于 2020-05-18T05:45:38.417 回答
0
一种可能的解决方案可能是:
使用REST parameter,可以创建一个数组并将每个动态变量(REST 参数项)作为对象添加到该数组中。
// function for handling a dynamic list of variables using REST parameters
const dynamicVars = (...theArgs) => {
let tempDynamicVars = [];
// as long as there are arguments, a new object is added to the array dynamicVars, creating a dynamic object list of variables
for (let args = 0; args < theArgs.length; args++){
const vName = `v${args}`;
tempDynamicVars = [...tempDynamicVars, {[vName]: theArgs[args]}]; //using spread operator
// dynamicVars.push({[vName]: theArgs[args]}); // or using push - same output
}
return tempDynamicVars;
}
// short version from above
// const dynamicVars = (...theArgs) => theArgs.map((e, i) => ({[`v${i}`]: e}));
// checking
const first = dynamicVars("F", 321);
console.log("Dynamic variable array:", first);
console.log(` - ${first.length} dynamic variables`);
console.log(" - second variable in the list is:", first[1], "\n");
console.log(dynamicVars("x, y, z"));
console.log(dynamicVars(1, 2, 3));
console.log(dynamicVars("a", "b", "c", "d"));
于 2020-11-15T17:21:25.067 回答