Mas*_*low 0 javascript refactoring loops
我是javascript的新手并试图重构一些代码,显然我在javascript中缺少一些我想学习的东西.所有5个列表框都选择了以下内容后,此代码会生成一个值:
function GetTotal() {
//_listSeverity = document.getElementById("_listSeverity");
function ParseListBoxvalue(listBox) {
return parseInt(GetListBoxValue(listBox),10);
}
_listSeverity = document.getElementById("<%= _listSeverity.ID %>");
_listAssociate = document.getElementById("<%= _listAssociateImpact.ID %>");
_listCustomerImpact = document.getElementById("<%= _listCustomerImpact.ID %>");
_listRegulatoryImpact = document.getElementById("<%= _listRegulatoryImpact.ID %>");
_listShareholderImpact = document.getElementById("<%= _listShareholderImpact.ID %>");
_calculatedTotal = (ParseListBoxvalue(_listAssociate) +
ParseListBoxvalue(_listSeverity) + ParseListBoxvalue(_listCustomerImpact)
+ParseListBoxvalue(_listRegulatoryImpact) + ParseListBoxvalue(_listShareholderImpact)
)/ 5;
if (isNaN(_calculatedTotal))
document.getElementById("_total").innerHTML = "Not enough information";
else
document.getElementById("_total").innerHTML = _calculatedTotal;
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试重构为for循环以消除一些代码重复.我尝试了很多方法,if(typeof _calculatedValue !='undefined')我在谷歌上发现,看看是否可以解决它.据我了解,我没有遇到范围问题,因为唯一的实际范围是由function(){}声明限制的.这永远不会产生价值.我意识到/ 5它还没有进入它,但这对我来说似乎并不是因为它总能产生一个NaN.
function GetTotal() {
//_listSeverity = document.getElementById("_listSeverity");
function ParseListBoxvalue(listBox) {
return parseInt(GetListBoxValue(listBox),10);
}
var _ListIds=new Array("<%= _listSeverity.ID %>","<%= _listAssociateImpact.ID %>",
"<%= _listCustomerImpact.ID %>", "<%= _listRegulatoryImpact.ID %>",
"<%= _listShareholderImpact.ID %>");
// _calculatedTotal = (ParseListBoxvalue(_listAssociate) +
// ParseListBoxvalue(_listSeverity) + ParseListBoxvalue(_listCustomerImpact)
// +ParseListBoxvalue(_listRegulatoryImpact) + ParseListBoxvalue(_listShareholderImpact)
// )/ 5;
for (i = 0; i < _ListIds.length; i++) {
if (i==0)
_calculatedTotal = ParseListBoxvalue(_ListIds[i]);
else
_calculatedTotal += ParseListBoxvalue(_ListIds[i]);
}
if (isNaN(_calculatedTotal))
document.getElementById("_total").innerHTML = "Not enough information";
else
document.getElementById("_total").innerHTML = _calculatedTotal;
}
Run Code Online (Sandbox Code Playgroud)
另一个功能应该没有关系,但这里是:
function GetListBoxValue(listBox) {
index = listBox.selectedIndex
try {
opt = listBox.options[index]
return opt.value;
} catch (e) { return null; }
}
Run Code Online (Sandbox Code Playgroud)
循环有什么问题?或者它是除了for循环导致重构不产生值的东西?
你没有打电话document.getElementById():
_calculatedTotal = ParseListBoxvalue(_ListIds[i]);
Run Code Online (Sandbox Code Playgroud)
应该
_calculatedTotal = ParseListBoxvalue(document.getElementById(_ListIds[i]));
Run Code Online (Sandbox Code Playgroud)
和其他分支类似.