[英]Add a key to an object with keys of an existing array with objects
我有一个对象array = [object1, object2, ...]
,每个对象都有一些键object1 = { key1: 'value1', ... }
。 我想以这种方式添加一个键:
$rootScope.array[i].newKey = 'someValue'
但angular告诉我$rootScope.array[i]
undefined
。
我从控制台注意到的是,对象获得了新密钥,但控制台仍然说明了相同的内容。
您应该使用小于且不小于或等于比较器。
$scope.init = function () {
for (i = 0; i < /* not <= */ $rootScope.meatTypes.length; i++) {
console.log("I am showing the meatypes:");
console.log($rootScope.meatTypes);
$rootScope.meatTypes[i].counter = '0';
counterOperations.setCounters(i, 0);
}
$rootScope.total = 0;
counterOperations.setTopCounter(0);
};
因为当i
等于$rootScope.meatTypes.length
$rootScope.meatTypes[i]
是undefined
。
您正在尝试访问不存在的阵列成员。
您需要创建一个新对象并将其推送到数组:
$rootScope.array.push({'key1': 'someValue'});
像这样你可以添加
$rootScope.array[i] = {}; // first we should create an object on that array location
$rootScope.array[i]['newKey'] = 'someValue'; // then only we can add values
编辑:
$scope.init = function () {
for (i = 0; i <= $rootScope.meatTypes.length; i++) {
console.log("I am showing the meatypes:");
console.log($rootScope.meatTypes);
**// This is needed**
$rootScope.meatTypes[i]={};// here we should tell that metaType[newItem] is an object other wise it treat it as undefined
$rootScope.meatTypes[i].counter = '0';
counterOperations.setCounters(i, 0);
}
$rootScope.total = 0;
counterOperations.setTopCounter(0);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.