Javascript:带有尾随字符的parseInt() [英] Javascript: parseInt() with trailing characters
问题描述
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
parseInt可能只将字符串的前导部分解释为整数值;它忽略了任何不能被解释为整数符号的一部分的字符,并且没有任何指示忽略任何这样的字符。
parseInt may interpret only a leading portion of string as an integer value; it ignores any characters that cannot be interpreted as part of the notation of an integer, and no indication is given that any such characters were ignored.
我更担心的是,在将来的某个时候, 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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!