質問

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.

役に立ちましたか?

解決

Generally you would do something like:

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

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

他のヒント

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

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

One possible solution may be:
Using REST parameter, one can create an array and add each dynamic variable (REST parameter item) as an object to that array.

// 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"));
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top