如何在 JavaScript 中定义对象变量结构?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22071236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I define an object variable structure in JavaScript?
提问by Leamphil
I want to define something like the following object structure, so I can populate it from a number of sources. What statements do I need to define it?
我想定义类似于以下对象结构的内容,以便我可以从多个来源填充它。我需要什么语句来定义它?
Offices[]
is an open-ended array as is rel[]
underneath it. All the elements are strings or maybe numbers.
Offices[]
是一个开放式阵列,就像rel[]
在它下面一样。所有元素都是字符串或数字。
Offices.name
Offices.desc
Offices.rel.type
Offices.rel.pt
回答by tymeJV
First I would make Offices
an array:
首先我会做Offices
一个数组:
var Offices = [];
Then populate that with objects:
然后用对象填充它:
var obj = {
name: "test",
desc: "Some description",
rel: []
}
Offices.push(obj);
Now you have your array (Offices
) populated with one object, so you could access it via Offices[0].desc
-- you can also populate the rel
array with Offices[0].rel.push(anotherObj)
现在您的数组 ( Offices
) 填充了一个对象,因此您可以通过访问它Offices[0].desc
——您也可以rel
使用Offices[0].rel.push(anotherObj)
回答by Tibos
If i understand correctly, you want to place multiple objects of the same type inside the Offices array. In order to easily build multiple objects of the same type you could use a constructor:
如果我理解正确,您想在 Offices 数组中放置多个相同类型的对象。为了轻松构建多个相同类型的对象,您可以使用构造函数:
function Office(name, desc, rel){
this.name = name;
this.desc = desc;
this.rel = rel;
}
Now you can declare an array to hold instances of the above type:
现在您可以声明一个数组来保存上述类型的实例:
var offices = [];
And you can add new instances like this:
您可以像这样添加新实例:
offices.push(new Office('John', 'good guy', []));
You can apply the same idea to the rel array to enforce the structure of the objects, or simply use object and array literals:
您可以将相同的想法应用于 rel 数组以强制执行对象的结构,或者简单地使用对象和数组文字:
offices.push(new Office('John', 'good guy', [{ type : 'M', pt : 3 }, { type : 'Q', pt : 2 }]);