Javascript equivalent of php's $object->{$stringvar} = 1 without eval()?
How do i create properties of an object from values of other variables开发者_如何学编程 without using the eval() function?
With array notation:
obj[stringvar] = 1;
var object = {}, stringvar = "name";
object[stringvar] = 1;
You can use other variables as property names like this:
var a = 'property';
var b = {};
b[a] = 'hello';
This can also then be accessed in he following way:
b.property;
Something like this with object literal notation:
var method = 'foo()';
// call it
myobject[method];
So you would do:
object[stringvar] = 1;
Use the bracket notation:
var o = { key: 'value' };
var member = 'key';
o[member] = 'oherValue';
var myobject = {};
var stringvar = "test";
myobject[stringvar] = 1;
Javascript objects allow for on-demand properties creation. Just set the property you want:
var object = {name:'A', id:1};
object.description = "Test";
alert(object.description);
精彩评论