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,438
  • 68
  • 55
  • 126
Mellon
  • 35,610
  • 77
  • 182
  • 262
  • 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,742
  • 2
  • 37
  • 50
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
  • 12,741
  • 1
  • 31
  • 33