[英]Setting nested properties in Javascript / AngularJS
我正在使用AngularJS,我想在控制器中设置一些配置变量。
例如:
$rootScope.config.showPosts.users = true;
$rootScope.config.showPosts.businesses = false;
$rootScope.config.showAds.businesses = true;
声明此类“嵌套”属性的正确方法是什么? 目前,我有:
$rootScope.config = [];
$rootScope.config.showPosts = [];
$rootScope.config.showAds = [];
// ^ as you can see, I am declaring each key of the array individually :(
$rootScope.config.showPosts.users = true;
$rootScope.config.showPosts.businesses = false;
$rootScope.config.showAds.businesses = true;
我不必在设置数组之前分别声明数组的每个级别,对吗? 提前致谢。
您可以使用对象杂物:
rootScope.config = {
showPosts: {
users: true,
businesses: false
},
showAds: {
businesses: true
}
};
问题是您试图在array
上设置property
。
你写了:
$rootScope.config.showPosts = [];
然后,您尝试编写:
$rootScope.config.showPosts.users = true;
因此, $rootScope.config.showPosts
应该是一个object
而不是此处的array
。 像这样更改代码:
$rootScope.config = {};
$rootScope.config.showPosts = {};
$rootScope.config.showAds = {};
我不必在设置数组之前分别声明数组的每个级别,对吗?
不,您不需要分别声明这些对象,可以像另一个答案中所示,在一个语句中声明整个配置object
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.