我有一个对象数组 array = [object1, object2, ...]
,每个对象都有一些键 object1 = { key1: 'value1', ... }
。我想这样添加一个键:
$rootScope.array[i].newKey = 'someValue'
但是Angular告诉我$rootScope.array[i]
是undefined
。
从控制台上看,我注意到对象得到了新键,但是控制台仍然显示相同的内容。
我有一个对象数组 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'});
$scope.init = function () { for (i = 0; i <= $rootScope.meatTypes.length; i++) { console.log("I am showing the meatypes:"); console.log($rootScope.meatTypes); $rootScope.meatTypes.push({'counter':0}); counterOperations.setCounters(i, 0); } $rootScope.total = 0; counterOperations.setTopCounter(0); };
- korteee像这样,您可以添加
$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);
};
$rootScope
中?例如$rootScope.array = array;
。 - Lulylulu$rootScope.meatTypes = [{}];
。 - korteee$rootScope.meatTypes = []
。 - Lulylulu