我可以更多地优化我的代码以减少行数吗?
我正在检查/传递单个数组元素?我可以用通用的方式重写吗?
for (var i = 0; i < $scope.studentReport.Students.length; i++)
{
if (_isValueNan($$scope.studentReport.Students[i].Age))
$$scope.studentReport.Students[i].Age = null;
if (_isValueNan($$scope.studentReport.Students[i].Number))
$$scope.studentReport.Students[i].Number = null;
if (_isValueNan($$scope.studentReport.Students[i].Height))
$$scope.studentReport.Students[i].Height = null;
}
var _isValueNan = function (item) {
var result = false;
if (typeof item == 'number' && isNaN(item))
result = true;
return result;
}
答案 0 :(得分:3)
参考Stumblor的回答:
for (var i = 0; i < $scope.studentReport.Students.length; i++) {
_checkValueNan($$scope.studentReport.Students[i], ["Age", "Number", "Height"]);
}
var _checkValueNan = function (item, values) {
values.forEach(function (val) {
if (typeof item[val] === 'number' && isNaN(item[val])) item[val] = null;
});
}
答案 1 :(得分:1)
您可以在函数内部使属性无效,并且还可以独立地传递item和property值。例如:
for (var i = 0; i < $scope.studentReport.Students.length; i++)
{
_checkValueNan($$scope.studentReport.Students[i], "Age");
_checkValueNan($$scope.studentReport.Students[i], "Number");
_checkValueNan($$scope.studentReport.Students[i], "Height");
}
var _checkValueNan = function (item, valueName) {
if (typeof item[valueName] == 'number' && isNaN(item[valueName]))
item[valueName] = null;
}
编辑: 从Vicky Gonsalves回答,你可以另外检查对象的任何属性,这可能是一个更具伸缩性的解决方案。
var _checkAllValueNan = function (item) {
for(var key in item) { // iterates all item properties
if (!item.hasOwnProperty(key)) continue; // ensures not prop of prototype
if (typeof item[key] == 'number' && isNaN(item[key])) item[key] = null;
}
}
for (var i = 0; i < $scope.studentReport.Students.length; i++)
{
_checkAllValueNan($scope.studentReport.Students[i]);
}