2

Let's say that be have two variables

var variable = "paypay";
var value = "this is the value of paypay!";

With the info above, is there a way to make paypay = "this is the value of paypay!"?

Julian Avar
  • 476
  • 1
  • 5
  • 24

4 Answers4

2

You can put it in a dictionary:

var obj = {};
obj[variable] = value;

Then obj.paypay is a variable which is now "this is the value of payday!".

ergonaut
  • 6,929
  • 1
  • 17
  • 47
  • `window[variable]=value;` will also work without the need of an object. so you can use `paypay` without having `obj.`paypay – NewToJS Nov 04 '15 at 02:28
1
var variable = "paypay";
var value = "this is the value of paypay!";

Some possibilities

var parent = {};

parent.variable  = value;  // this is the value of paypay!
parent[variable] = value;  // this is the value of paypay!
parent["paypay"] = value;  // this is the value of paypay!
parent.paypay    = value;  // this is the value of paypay!
var "paypay"     = value;  // error Unexpected string
var  paypay      = value;  // this is the value of paypay!
Scott Stensland
  • 26,870
  • 12
  • 93
  • 104
1

Assuming that you are properly scoped into a closure or otherwise... then you can cheat and kinda use the "this";

Example:

this[variable] = value;
console.log(variable);
Nick Sharp
  • 1,881
  • 12
  • 16
  • But in seriousness, I'd go with ergonaut's suggestion, and stuff it into an object, probably safer than playing with "this" if you're at your current Javascript comfort level. – Nick Sharp Nov 04 '15 at 02:14
0
eval("var " + variable + "=" + value);

that is a solution even if using eval() function is not always recommended.