gpt4 book ai didi

javascript - 将两个变量相加得到 Nan

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

我一直在尝试添加下面代码中显示的两个不同变量,但无论我做什么,结果都是 Nan,我在这里做错了什么吗?我尝试了一段时间,但我找不到我的代码有什么问题!

                            <script type="text/javascript">
function showEstimate() {
switch (document.getElementById("cboCar").value) {
case "A":
document.getElementById("imgCar").src= "images/Accord.jpg";
carPrice = document.getElementById("txtEstPr").value;
break;
case "C":
document.getElementById("imgCar").src= "images/Civic.jpg";
carPrice = document.getElementById("txtEstPr").value;
break;
} // end of switch block.
//here, the UI has done processing cars pics
//display the price for cars
document.getElementById("txtEstPr").value= "$" + carPrice;
// end of the function named



{
var vchkSt= (300.99).toFixed();
var vchkLe= (750.99).toFixed();
var vchkGps= (1600.00).toFixed();
var tTotal = 0;
carPrice = Number(document.getElementById("txtBasePr").value);


if (document.getElementById("chkSt").checked)
tTotal += parseFloat(carPrice) + parseFloat(vchkSt);

if (document.getElementById("chkLe").checked )
tTotal += parseFloat(carPrice) + parseFloat(vchkLe);

if (document.getElementById("chkGps").checked ==true )
tTotal += parseFloat(carPrice) + parseFloat(vchkGps);


//displaying the total
document.getElementById("txtEstPr").value = "$" + tTotal;
}
} // end of function showEstimate

</script>

最佳答案

您没有调用 toFixed 函数,而是将该函数分配给 chkStchkLechkGps :

var chkSt= (300.99).toFixed;
var chkLe= (750.99).toFixed;
var chkGps= (1600.00).toFixed;

相反,它应该是:

var chkSt= (300.99).toFixed();
var chkLe= (750.99).toFixed();
var chkGps= (1600.00).toFixed();

还有

Number(carPrice = document.getElementById("txtEstPr").value);

没有任何意义。无需将赋值包装在 Number 函数中。看起来您正在尝试将值作为数字分配给 carPrice,这可以简单地完成:

carPrice = +document.getElementById("txtEstPr").value;

carPrice = Number(document.getElementById("txtEstPr").value);

此外,您还需要为每个后续复选框重新分配 tTotal。您可能应该使用:

if (document.getElementById("chkSt").checked) {
tTotal += parseFloat(carPrice) + parseFloat(chkSt);
// ^
}

使用var tTotal = 0来初始化变量。

关于javascript - 将两个变量相加得到 Nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27259040/

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