本文介绍了Javascript:带有尾随字符的parseInt()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

parseInt(7em,10); 在我测试的所有浏览器中返回 7 [*]。但我能依靠吗?

parseInt("7em", 10); returns 7 in all browsers I tested [*]. But can I rely on this?

我问的原因是,我想基于em执行一些计算,比如

The reason I ask is, that I want to perform some calculations based on em, like

/* elem1.style.top uses em units */
elem2.style.top = parseInt(elem1.style.top, 10) + 1 + "em";

我可以使用正则表达式执行此操作,但parseInt更易于使用,并且可能更快一些。或者是否有其他解决方案(可能使用jQuery)?

I could do this with regular expressions, but parseInt is easier to use, and probably a bit faster. Or is there another solution (maybe using jQuery)?

[*]到目前为止测试:IE 6,IE 8,Safari 4,Firefox 3.6,Opera 10.5

[*] Tested so far on: IE 6, IE 8, Safari 4, Firefox 3.6, Opera 10.5

推荐答案

这是符合标准的行为。 ECMA-262第15.1.2.2节规定

That is the behavior according to the standard. ECMA-262 section 15.1.2.2 states that

我更担心的是,在将来的某个时候, elem2.style.top 的单位将会改变。在这种情况下,此代码可能会将 200px 转换为 200em ,这可能会造成很大的混乱。

I'd be more worried that at some point in the future the units of elem2.style.top will change. In that case, this code could be turning 200px into 200em, which could cause a great deal of confusion.

这篇关于Javascript:带有尾随字符的parseInt()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 18:11