我希望使我的代码更加高效。我这样写是因为我找不到通过对象属性各自的键访问对象属性的方法。理想情况下,我希望使用 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;
关于javascript - 通过键访问对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37442317/