簡體   English   中英

通過鍵訪問對象屬性

[英]Accessing an object property by key

我希望使我的代碼更高效。 之所以這樣寫,是因為我找不到通過其各自的鍵訪問對象屬性的方法。 理想情況下,我想使用一個for循環來縮短這段龐大的代碼。 我願意重組對象,如果有幫助的話。

if (response.data[i].code == 'P01') {
  $scope.production['P01'] += response.data[i].hours;
} else if (response.data[i].code == 'P02') {
  $scope.production['P02'] += response.data[i].hours;
} else if (response.data[i].code == 'P03') {
  $scope.production['P03'] += response.data[i].hours;
} else if (response.data[i].code == 'P04') {
  $scope.production['P04'] += response.data[i].hours;
} else if (response.data[i].code == 'P05') {
  $scope.production['P05'] += response.data[i].hours;
} else if (response.data[i].code == 'P06') {
  $scope.production['P06'] += response.data[i].hours;
} else if (response.data[i].code == 'P07') {
  $scope.production['P07'] += response.data[i].hours;
} else if (response.data[i].code == 'P08') {
  $scope.production['P08'] += response.data[i].hours;
}

可以想象,$ scope.production是這樣的對象:

$scope.production = {'P01' :0, 'P02' : 0, 'P03' :0};
var data = response.data[i];
$scope.production[data.code] += data.hours;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM