开发者

Javascript equivalent of php's $object->{$stringvar} = 1 without eval()?

开发者 https://www.devze.com 2023-03-28 21:24 出处:网络
How do i create properties of an object from values of other variables开发者_如何学编程 without using the eval() function?With array notation:

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消