javascript 中的嵌套对象,最佳实践
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7942398/
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
Nested objects in javascript, best practices
提问by Johan
I would like to know the correct way to create a nested object in javascript. I want a base object called "defaultsettings". It should have 2 properties (object type): ajaxsettings and uisettings. I know that i can write something like
我想知道在 javascript 中创建嵌套对象的正确方法。我想要一个名为“defaultsettings”的基础对象。它应该有 2 个属性(对象类型):ajaxsettings 和 uisettings。我知道我可以写一些类似的东西
var defaultsettings = new Object();
var ajaxsettings = new Object();
defaultsettings.ajaxsettings = ajaxsettings.. etc.
But what i want to know is how to type it this way (that i suppose is a more correct way of doing it):
但我想知道的是如何以这种方式输入(我认为这是一种更正确的方式):
var defaultsettings = {
var ajaxsettings = { ... }
};
I suppose you get the idea. Thanks!
我想你明白了。谢谢!
回答by nnnnnn
If you know the settings in advance you can define it in a single statement:
如果您事先知道设置,您可以在单个语句中定义它:
var defaultsettings = {
ajaxsettings : { "ak1" : "v1", "ak2" : "v2", etc. },
uisettings : { "ui1" : "v1", "ui22" : "v2", etc }
};
If you don't know the values in advance you can just define the top level object and then add properties:
如果您事先不知道这些值,您可以定义顶级对象,然后添加属性:
var defaultsettings = { };
defaultsettings["ajaxsettings"] = {};
defaultsettings["ajaxsettings"]["somekey"] = "some value";
Or half-way between the two, define the top level with nested empty objects as properties and then add properties to those nested objects:
或者介于两者之间,将顶层与嵌套的空对象定义为属性,然后为这些嵌套对象添加属性:
var defaultsettings = {
ajaxsettings : { },
uisettings : { }
};
defaultsettings["ajaxsettings"]["somekey"] = "some value";
defaultsettings["uisettings"]["somekey"] = "some value";
You can nest as deep as you like using the above techniques, and anywhere that you have a string literal in the square brackets you can use a variable:
您可以使用上述技术嵌套任意深,并且在方括号中有字符串文字的任何地方都可以使用变量:
var keyname = "ajaxsettings";
var defaultsettings = {};
defaultsettings[keyname] = {};
defaultsettings[keyname]["some key"] = "some value";
Note that you can notuse variables for key names in the { } literal syntax.
请注意,您不能在 { } 文字语法中为键名使用变量。
回答by Niet the Dark Absol
var defaultsettings = {
ajaxsettings: {
...
},
uisettings: {
...
}
};
回答by Brian
var defaultSettings = {
ajaxsettings: {},
uisettings: {}
};
Take a look at this site: http://www.json.org/
看看这个网站:http: //www.json.org/
Also, you can try calling JSON.stringify() on one of your objects from the browser to see the json format. You'd have to do this in the console or a test page.
此外,您可以尝试从浏览器中对您的对象之一调用 JSON.stringify() 以查看 json 格式。您必须在控制台或测试页面中执行此操作。