gpt4 book ai didi

javascript - 通过调用方法检查数组的单个元素

转载 作者:行者123 更新时间:2023-11-28 15:18:11 24 4
gpt4 key购买 nike

我可以进一步优化我的代码以减少行数吗?

我正在检查/传递单个数组元素?我可以用通用的方式重写它吗?

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;
}

最佳答案

引用 Stumblo 的回答:

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;
});
}

关于javascript - 通过调用方法检查数组的单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32690681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com