0

I defined a variable which will get user's input:

var input = USER_INPUT;

then, I create an object which will use this input as an variable name inside the object:

var obj = { input: Car.newCar(...)}

Then, I try to access the obj[input], but it returns to me undefined. Is it so that in javascript, I can not use variable as an object's variable name?

If I would like to define a object which has vary variable name and variable value, how can I do?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mellon
  • 37,586
  • 78
  • 186
  • 264
  • This is a possible duplicate of http://stackoverflow.com/questions/4119324/passing-in-dynamic-keyvalue-pairs-to-an-object-literal – rubiii Apr 15 '11 at 07:39

2 Answers2

2

So I guess you want the store the input under a key named after the input itself.
You can assign the value returned by Car.newCar() by using the [] method:

var input = "some text";
var obj = {};

obj[input] = Car.newCar();
rubiii
  • 6,903
  • 2
  • 38
  • 51
1

Sorry changed my answer after re-reading the question

var USER_INPUT = 'something';
var obj = {};
obj[USER_INPUT] = 'value';

obj.something ; //# => value
obj['something'] ; //# => value

obj[USER_INPUT]; //# => value
James Kyburz
  • 13,775
  • 1
  • 32
  • 33