[英]Use variable for property name in JavaScript literal?
I know we can create new properties in Javascript objects during runtime but could that property be assigned a value too? 我知道我们可以在运行时在Javascript对象中创建新属性,但是该属性是否也可以赋值? For example. 例如。
var value = "New value";
var table = new Object();
var newValue = table[value];
Now, I know that value table has a new property called "value". 现在,我知道值表有一个名为“value”的新属性。 but does that "value key contains the information as " New Value". So, does that mean now table object is like following: 但是这个“值键”包含的信息是“新值”。那么,这是否意味着现在表对象如下:
table = {
value:"New Value";
}
You're confusing accessing with assigning. 你在分配访问时会感到困惑。
// Assigns a variable named 'value' with a value of 'New Value'.
var value = "New value";
// Creates a variable named 'table' as a blank Object.
var table = new Object(); // Alternatively - table = {};
// Attempts to access "New Value" from object "table" which returns undefined.
var newValue = table[value];
If you want to assign properties to an object you do so like this: 如果要为对象分配属性,请执行以下操作:
// Assumes table is still an object.
table['key'] = 'value';
// Note that I almost _always_ opt for the variable['key'] notation over
// the variable.key notation because it allows you to use keys
// that would otherwise not be valid as identifiers.
table['Some Key'] = 'Some Value'; // This works.
table.Some Key = 'Some Value'; // This does not.
Later, when you want to retrieve that value and store it in a new variable, that's when you do this: 稍后,当您想要检索该值并将其存储在新变量中时,就是这样:
var newVariable = table['key'];
Hopefully that clarifies some. 希望澄清一些。 Please let me know if I can expand on any part of it. 如果我能扩展它的任何部分,请告诉我。
no. 没有。 your statement 你的陈述
var newValue = table[value];
is not setting anything, and since at the time when you created table
you didn't assign any property, newValue
will be undefined
. 没有设置任何东西,因为在你创建table
你没有分配任何属性, newValue
将是undefined
。
If you have a value
variable that is assigned a value, and you want to assign that value to table under the key value
, you want to do 如果你有一个value
分配一个值变量,并且希望下键分配一个值表value
,你想干什么
table['value'] = value;
or alternatively 或者
table.value = value
Erm, no, I don't think you've got it quite right. 呃,不,我不认为你说得对。
All that does is assign undefined
to newValue
, because you're trying to access table
's " New Value
" property, which doesn't exist. 所有这一切都是将undefined
分配给newValue
,因为您正在尝试访问table
的“ New Value
”属性,该属性不存在。
What I think you're trying to do is this: 我认为你要做的是:
var value = "New value";
var table = {};
table.value = value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.