[英]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.