防止连接 [英] Preventing concatenation

查看:154
本文介绍了防止连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了13年的JavaScript,但我在过去的几个月里重新发现了它作为一种编写程序的方式,任何访问网页的人都可以使用它而无需安装任何东西。请参阅示例

I've been writing JavaScript on and off for 13 years, but I sort of rediscovered it in the past few months as a way of writing programs that can be used by anyone visiting a web page without installing anything. See for example.

我最近发现的showstopper是因为JavaScript在设计上是松散类型的,所以当我希望它添加数字时,它会保持连接字符串。这是不可预测的。一个例程工作好几天,然后当我输入不同的数据时问题就出现了,我最终得到了一个不可思议的大数字。

The showstopper I've recently discovered is that because JavaScript is loosely typed by design, it keeps concatenating strings when I want it to add numbers. And it's unpredictable. One routine worked fine for several days then when I fed different data into it the problem hit and I ended up with an impossibly big number.

有时候我运气不好这通过在一个术语周围加上(),有时候我不得不求助于 parseInt()或<$ c一个学期的$ c> parseFloat()。它提醒我一点点试图通过在一个(常量)项上放置.00来强制将结果放入C中。我只是通过 parseFloat()尝试 + = 来自我已经加载的数组中的某些东西关于一切。

Sometimes I've had luck preventing this by putting ( ) around one term, sometimes I've had to resort to parseInt() or parseFloat() on one term. It reminds me a little of trying to force a float result in C by putting a .00 on one (constant) term. I just had it happen when trying to += something from an array that I was already loading by doing parseFloat() on everything.

这是否只会发生?如果我每次添加至少一个术语时使用 parseInt() parseFloat(),那么防止它?我在Linux下使用Firefox 6进行编写,但浏览器的可移植性也是一个问题。

Does this only happen in addition? If I use parseInt() or parseFloat() on at least one of the terms each time I add, will that prevent it? I'm using Firefox 6 under Linux to write with, but portability across browsers is also a concern.

推荐答案

规范说明了加法运算符

如果Type( lprim )是String或Type( rprim )是String,那么

返回String是连接ToString( lprim )后跟ToString( rprim

If Type(lprim) is String or Type(rprim) is String, then
Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)



<的结果p>这意味着如果至少有一个运算符是字符串,则会发生字符串连接。

Which means that if at least one operator is a string, string concatenation will take place.


如果我使用 parseInt() parseFloat()每次添加时至少有一个术语会阻止它吗?

If I use parseInt() or parseFloat() on at least one of the terms each time I add, will that prevent it?

不,所有操作数必须是数字。

No, all operands have to be numbers.

您可以轻松地将任何数字字符串转换为一个使用 一元加运算符(如果您已经处理过,它将不会更改该值数字):

You can easily convert any numerical string into a number using the unary plus operator (it won't change the value if you are already dealing with a number):

var c = +a + +b;

这篇关于防止连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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