简体   繁体   English

这个javascript对象数组如何工作?

[英]How does this javascript object array work?

I am trying to understand something very basic. 我想要了解一些非常基本的东西。 If I have an object like this: 如果我有这样的对象:

var topics = {}

And I do this: 我这样做:

topics[name] = ["chapter 1", "chapter 2", "chapter 3"];

When I log this object, I don't see the name attribute. 当我记录这个对象时,我没有看到name属性。 What have I done exactly? 我到底做了什么? Have I created a key called name with the value of an array? 我是否创建了一个名为name的键,其值为数组?

Of course I know I can do that by just doing 当然,我知道我可以做到这一点

topics.name =  ["chapter 1", "chapter 2", "chapter 3"];

But then what is this doing? 那么这是做什么的呢?

topics[name] = ["chapter 1", "chapter 2", "chapter 3"];

Could someone please clarify? 有人可以澄清一下吗?

Your are creating a property on the object with a name based on the value of the name variable. 您正在对象上创建一个属性,其名称基于name变量的值。 If you want to create a property called name in that way you need to do: 如果要以这种方式创建名为name的属性,则需要执行以下操作:

topics["name"] = ["chapter 1", "chapter 2", "chapter 3"];

When you use the [] notation it expects an expression in between, that translates to a string. 当你使用[]表示法时,它需要一个表达式,它转换为一个字符串。

Using name not enclosed in quotes 'name' it assumes you are using a variable called name. 使用name不能用引号括起来'name'它假设你使用的是所谓的名称变量。

Which in your case is undefined . 在你的情况下, undefined

The correct usage would be 正确的用法是

topics["name"] = ["chapter 1", "chapter 2", "chapter 3"];

If you want to use a variable you can do things like 如果你想使用变量,你可以做类似的事情

var prop = 'name';
var topics = {};

topics[prop] = ["chapter 1", "chapter 2", "chapter 3"];

this will create the name property on the object.. useful for dynamic/automatic creation/filling of objects.. 这将在对象上创建name属性..对于动态/自动创建/填充对象很有用。

That should generate an error, unless you have variable name defined as a string or a number. 除非您将变量name定义为字符串或数字,否则应生成错误。

These three are equivalent: 这三个是等价的:

var name = "key";
topics[name] = "value";

topics["key"] = "value";

topics.key = "value";

There are generally three ways to distinguish: 通常有三种方法可以区分:

topics.name
topics["name"]
topics[name]

The first two are equivalent. 前两个是等价的。 So .xxx represents the literal key xxx , as does ["xxx"] . 因此.xxx表示文字键xxx["xxx"]

The last one will use whatever the name variable contains. 最后一个将使用name变量包含的任何内容。 Eg: 例如:

var name = "test";
topics[name] = 123; // topics["test"] now exists

The resulting structure can be seen in the following screen capture. 在下面的屏幕截图中可以看到生成的结构。 As stated by mck89, you probably want to use the "name" syntax 如mck89所述,您可能希望使用"name"语法

在此输入图像描述

如果您的代码没有导致ReferenceError ,您可能已经在名为name全局作用域中创建了一个变量,并创建了name的内容的新属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM