简体   繁体   English

Javascript变量未添加结果,变量为何充当字符串?

[英]Javascript variables not adding the result, variables are act as string why?

Why error ? 为什么会出错?

expected results = 1360000 预期结果= 1360000

result = 1000000360000 结果= 1000000360000

 <script> function hitungJumlah() { var jumlah = document.getElementById("pinjam").value; var lama = document.getElementById("kembalinya").value; var bunga = lama * 12/100; var biaya = document.getElementById("biaya").value = jumlah * bunga; document.getElementById("total").value = jumlah + biaya; } </script> 

在此处输入图片说明

Because it's read your data as string use parseInt() function to make your data as Integer 因为它以string读取您的数据,所以使用parseInt()函数使您的数据成为Integer

Try with this 试试这个

parseInt(jumlah) + parseInt(biaya)

Beacuse 1000000 and 360000 act as string . 因为1000000360000充当字符串。 + is also used for concatination in javascript +也用于javascript隐藏

Because the * operator wont type coerce like + operator. 因为*运算符不会像+运算符那样强制输入。 Besides you may not have to use document.getElementById() all the time. 此外,您可能不必一直使用document.getElementById() You might simply do; 您可以简单地做到;

<script>
function hitungJumlah() {
  var  jumlah = Number(pinjam.value),
         lama = Number(kembalinya.value),
        bunga = lama * 12/100;
  biaya.value = jumlah * bunga;
  total.value = jumlah + biaya;
}
</script>

Though parseInt() and Number() have differences. 虽然parseInt()Number()有区别。 While parseInt("42*10") would result 42, as a number object constructor Number("42*10") would result a NaN . 虽然parseInt("42*10")将产生42,而数字对象构造函数Number("42*10")将产生NaN

So be careful playing with them. 因此,请小心与他们一起玩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM