开发者

Add property to object with key in JavaScript

I have a simple code like this:

var name = 'lin开发者_开发百科e1';
var obj = {};
obj.name = [0, 1];
console.log(obj);

Key of property is name. But I want to make key='line'. Can you help me?


If I understand correctly, and you want to use the value of the name variable as the property name, you can use this syntax:

obj[name] = [0, 1]; //obj.line1 will be [0, 1]

Object properties can also be accessed with the same syntax arrays use. It is handy in situations like this one.


Try,

obj[name]

or

obj["line1"]

This is known as the bracket notation, and can be used to access any property of an object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜