我希望让我的代码更有效率。我这样写的是因为我找不到通过各自键访问对象属性的方法。理想情况下,我希望使用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};
答案 0 :(得分:3)
var data = response.data[i];
$scope.production[data.code] += data.hours;