在JavaScript文字中使用变量作为属性名称?

Vik*_*Vik 3 javascript

我是JavaScript的新手,并试图用它做一些实验.我有一个问题.我知道我们可以在运行时在Javascript对象中创建新属性,但是也可以为该属性分配值.例如.

var value = "New value";

var table = new Object();

var newValue = table[value];
Run Code Online (Sandbox Code Playgroud)

现在,我知道值表有一个名为"value"的新属性.但是这个"值键"包含的信息是"新值".那么,这是否意味着现在表对象如下:

table = {
value:"New Value";
}
Run Code Online (Sandbox Code Playgroud)

感谢您提前帮助的人.

-Vik

g.d*_*d.c 5

你在分配访问时会感到困惑.

// 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];
Run Code Online (Sandbox Code Playgroud)

如果要为对象分配属性,请执行以下操作:

// 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.
Run Code Online (Sandbox Code Playgroud)

稍后,当您想要检索该值并将其存储在新变量中时,就是这样:

var newVariable = table['key'];
Run Code Online (Sandbox Code Playgroud)

希望澄清一些.如果我能扩展它的任何部分,请告诉我.