Javascript添加无法正常工作 [英] Javascript Addition wont work

查看:83
本文介绍了Javascript添加无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我如何将这些变量加起来:

can anybody tell me how to add up these variables:

var preciopag = document.valores.T1.value;

var libras = document.valores.T2.value;

var serviciocom = 5.00

var contador1 = 0;

var contador2 = 0;

var tramite = 0;

var enviopty = 0;

var ITBMS = 0;

var Total = preciopag + serviciocom + enviopty + tramite + ITBMS;

预先感谢。

推荐答案

元素的始终是字符串,因此 + 将导致串联,而不是加法。

The value of elements is always a string, so + will result in concatenation, not addition.

在检索值时将字符串转换为数字:

Convert from string to number when retrieving the values:

var preciopag = +document.valores.T1.value;
var libras = +document.valores.T2.value;

我曾经用过 + 将查看整个字符串,但您可能会看到 parseFloat ,它将在最后忽略任何无效的内容;

There I've used +, which will look at the entire string, but you might look at parseFloat which will ignore anything invalid at the end; it depends entirely on what you want to do with semi-valid input.

演示:

var preciopag = "5";   // Simulating document.valores.T1.value
var libras = "10";     // Simulating document.valores.T2.value
var serviciocom = 5.00
var contador1 = 0;
var contador2 = 0;
var tramite = 0;
var enviopty = 0;
var ITBMS = 0;
var Total = preciopag + serviciocom + enviopty + tramite + ITBMS;

snippet.log(Total); // "55000" - wrong

// Instead:
preciopag = +"5";    // Simulating document.valores.T1.value 
libras = +"10";      // Simulating document.valores.T2.value
Total = preciopag + serviciocom + enviopty + tramite + ITBMS;

snippet.log(Total); // "10" - right

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

这篇关于Javascript添加无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆