在JavaScript文字中使用变量作为属性名称? [英] Use variable for property name in JavaScript literal?

查看:787
本文介绍了在JavaScript文字中使用变量作为属性名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to JavaScript and trying to do some experiment with it. I have one question. I know we can create new properties in Javascript objects during runtime but would that property can be assigned a value too. For example.

var value = "New value";

var table = new Object();

var newValue = table[value];

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

Now, I know that value table has a new property called "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";
}

Thanks提前为你提供帮助。

Thanks for your help in advance guys.

-Vik

推荐答案

你'分配访问令人困惑。

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.

这篇关于在JavaScript文字中使用变量作为属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆