Using variable name in JS object?
I defined a variab开发者_StackOverflowle 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?
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();
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
精彩评论