声明可以以这种方式分配的对象
Declare object that can be assigned in this manner
假设我想要一个 javascript 对象,可以使用下面类似的语法进行分配;
parent.child1.property1 = "xx"
parent.child1.property2 = "xx"
parent.child1.property3 = "yy"
parent.child2.property1 = "xx"
parent.child2.property2 = "xx"
parent.child2.property3 = "yy"
如果可以的话,这样的对象应该如何声明?
可能是这样的
var parent =
{child1: {property1:"xx",property2:"xx",property3:"yy"},
child2: {property1:"xx",property2:"xx",property3:"yy"}};
Aggaton 的示例可以工作,但是您需要调用索引,因为方括号会创建一个数组。他已经更新了他的答案。
如果您想像在原始文件中指定的那样使用点符号,只需将数据设置为嵌套对象即可:
var parent = {
child1: {
property1: "one",
property2: "two",
property3: "three"
},
child2: {
property1: "one",
property2: "two",
property3: "three"
}
};
console.log(parent.child1.property1); // "one"
console.log(parent.child2.property2); // "two"
还有一个有点相似的答案,向您展示了良好的符号:Nested JSON objects - do I have to use arrays for everything?
假设我想要一个 javascript 对象,可以使用下面类似的语法进行分配;
parent.child1.property1 = "xx"
parent.child1.property2 = "xx"
parent.child1.property3 = "yy"
parent.child2.property1 = "xx"
parent.child2.property2 = "xx"
parent.child2.property3 = "yy"
如果可以的话,这样的对象应该如何声明?
可能是这样的
var parent =
{child1: {property1:"xx",property2:"xx",property3:"yy"},
child2: {property1:"xx",property2:"xx",property3:"yy"}};
Aggaton 的示例可以工作,但是您需要调用索引,因为方括号会创建一个数组。他已经更新了他的答案。
如果您想像在原始文件中指定的那样使用点符号,只需将数据设置为嵌套对象即可:
var parent = {
child1: {
property1: "one",
property2: "two",
property3: "three"
},
child2: {
property1: "one",
property2: "two",
property3: "three"
}
};
console.log(parent.child1.property1); // "one"
console.log(parent.child2.property2); // "two"
还有一个有点相似的答案,向您展示了良好的符号:Nested JSON objects - do I have to use arrays for everything?