开发者

Why can't one object's property value be used as a property name in another object?

The following gives me an error in my JS console (firebug):

var obj1 = {name:'king', val:20}, obj2, objName = obj1.name;
obj2 = {obj1.name:obj1.val};

But 开发者_开发技巧the following works just fine:

var obj1 = {name:'king', val:20}, obj2, objName = obj1.name;
obj2 = {objName:obj1.val};

The exact error is: "missing : after property id". I don't need a work-around, I'm curious to know what the problem is here.


Expressions aren't allowed left of ':' inside of object literals.

Please have a look here: Why does my code return the error "missing : after property id" in JavaScript? and here http://www.dyn-web.com/tutorials/obj_lit.php


I haven't used JS for a while, so correct if I'm wrong

If you use this:

obj = {name : value};

then you are creating a new object with a new field called name.

So when you tried to do

obj2 = {obj1.name : obj1.val};

you were attempting to create a field called obj1.name, which is not a valid identifer.

For the second one

obj2 = {objName : obj1.val};

the name objName is a valid identifier, so this works. But it is not using the variable objName, but is creating a new one as a field for obj2


I think you're confused about why the 2nd one works.

var obj1 = {name:'king', val:20}, obj2, objName = obj1.name;
obj2 = {objName:obj1.val};

The name of the property in obj2 won't actually be "king." It will be "objName" -- just the string "objName" not the value of the variable objName.

If you want to dynamically assign property names, it's pretty simple.

var obj1 = {name:'king', val:20}, obj2;
obj2 = {};
obj2[obj1.name]=obj1.val;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜