为什么if语句在这个else之下执行?
问题描述:
我一直在试图弄清楚这一点。出于某种原因,第一,如果下为什么if语句在这个else之下执行?
else语句,如果(customerType =“T”)
不断执行即使customerType不等于“T”,所以discountPercent不断成为0.40此事没有什么输入是除非customerType等于“R”,“C”或“T”。谁能帮我吗?
var $ = function (id) {
return document.getElementById(id);
}
var calculate_click = function() {
var customerType = $("type").value.toUpperCase;
var invoiceSubtotal = parseFloat($("subtotal").value);
$("subtotal").value = invoiceSubtotal.toFixed(2);
var discountPercent = .0;
var valid = false;
if (customerType == "R") {
valid = true;
if (invoiceSubtotal < 100){
discountPercent = .0;
}
else if (invoiceSubtotal >= 100 && invoiceSubtotal < 250){
discountPercent = .1;
}
else if (invoiceSubtotal >= 250 && invoiceSubtotal < 500){
discountPercent = .25;
}
else if (invoiceSubtotal >= 500){
discountPercent = .30;
}
}
else if (customerType == "C") {
valid = true;
discountPercent = .20;
}
else if (customerType = "T"){
valid = true;
if(invoiceSubtotal < 500){
discountPercent = .40;
}
if(invoiceSubtotal >= 500){
discountPercent = .50;
}
}
else if(!valid){
discountPercent = .10;
}
var discountAmount = invoiceSubtotal * discountPercent;
var invoiceTotal = invoiceSubtotal - discountAmount;
$("percent").value = (discountPercent * 100).toFixed(2) ;
$("discount").value = discountAmount.toFixed(2);
$("total").value = invoiceTotal.toFixed(2);
$("type").focus;
}
答
else if (customerType = 'T')
始终计算为true
,因为它没有任何的比较,它被分配“T”值customerType。可能你想做else if (customerType == 'T')
?
答
你大概的意思是:
else if (customerType == "T")
^
typo here corrected
因为
else if (customerType = "T")
是完全相同的:
else if ("T")
“T” 被评估为真,这句话永远是真实的无论。
您正在为客户类型分配'“T”'。我可能会建议一个'switch'? – 2014-09-28 23:51:48
你可能意思别的if(customerType ==“T”) – 2014-09-28 23:52:11
谢谢,这些错误总是让我发疯。 – 2014-09-29 00:02:58