gpt4 book ai didi

Javascript 加法给我 NaN

转载 作者:行者123 更新时间:2023-12-01 02:27:55 27 4
gpt4 key购买 nike

我有一个 Javascript 代码,如下所示。一切都工作正常,除了净值(所有总值的总和)为 NaN。我已经使用了 parseFloat() 但结果仍然是 NaN。但我得到了所有的总值(value)。欢迎任何帮助。

window.onkeyup=function() {

var items = document.querySelectorAll(".item");
var itemsArray = Array.prototype.slice.call(items,0);
var unit, rate, total, net, tax, margin, rateamount = 0;
itemsArray.forEach(function(el){
unit = el.querySelector('input[name="unit[]"]').value;
rate = el.querySelector('input[name="rate[]"]').value;
tax = el.querySelector('input[name="tax[]"]').value;
margin = el.querySelector('input[name="margin[]"]').value;
el.querySelector('input[id="marginrate[]"]').options[el.querySelector('input[id="marginrate[]"]').selectedIndex].text;
var rateMargin =el.querySelector('[name="marginrate[]"]').selectedIndex;



if (rateMargin==1) {rateamount=margin/100}
if (rateMargin==0) {rateamount=margin}


total = (parseFloat(unit * rate) + parseFloat(rateamount))-parseFloat(tax/100);
alert(total);
el.querySelector('input[name="total[]"]').value = total;
net+= parseFloat(total);
});

document.getElementById('net').value=net;
}

最佳答案

您从未初始化过 net,因此当您执行 net += parseFloat(total); 时,您将向 undefined 添加一个数字,这会导致 NaN。您需要将其初始化为0

您还应该对从输入读取的值调用 parseFloat,而不是对算术运算的结果调用(它们总是返回数字,您不需要解析它们)。

window.onkeyup = function() {

var items = document.querySelectorAll(".item");
var itemsArray = Array.prototype.slice.call(items, 0);
var unit, rate, total, net = 0, tax, margin, rateamount = 0;
itemsArray.forEach(function(el) {
unit = el.querySelector('input[name="unit[]"]').value;
rate = el.querySelector('input[name="rate[]"]').value;
tax = el.querySelector('input[name="tax[]"]').value;
margin = el.querySelector('input[name="margin[]"]').value;
el.querySelector('input[id="marginrate[]"]').options[el.querySelector('input[id="marginrate[]"]').selectedIndex].text;
var rateMargin = el.querySelector('[name="marginrate[]"]').selectedIndex;

if (rateMargin == 1) {
rateamount = margin / 100
} else if (rateMargin == 0) {
rateamount = margin
}

total = (parseFloat(unit) * parseFloat(rate) + parseFloat(rateamount)) - parseFloat(tax) / 100;
alert(total);
el.querySelector('input[name="total[]"]').value = total;
net += total;
});

document.getElementById('net').value = net;
}

关于Javascript 加法给我 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48595444/

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