带有变量的对象键名 [英] Object key name with a variable
本文介绍了带有变量的对象键名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个对象,该对象的一个键名取自变量.
I am trying to make an object which has one key name taken from a variable.
var key="KeyName"
var obj={
key:"value"
}
当我想访问KeyName"密钥时,我不能,因为我刚刚创建了一个名为key"而不是KeyName"的密钥.我在这里找到了一个解决方案:
When I want to access the "KeyName" key,I can't because I have just created a key with the name "key" not "KeyName". I found a soution here :
var key="KeyName"
var obj={
[key]:"value"
}
但它不起作用.怎么办?
But it doesn't work. What to do?
推荐答案
你可以这样:先初始化对象,用括号[]
设置key值.
You can do it like this: first initialize the object and use brackets []
to set key value.
var obj = {};
var key = "KeyName";
obj[key] = "value";
这篇关于带有变量的对象键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文