admin管理员组文章数量:1391995
parseInt("7em", 10);
returns 7
in all browsers I tested [*]. But can I rely on this?
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";
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)?
[*] Tested so far on: IE 6, IE 8, Safari 4, Firefox 3.6, Opera 10.5
parseInt("7em", 10);
returns 7
in all browsers I tested [*]. But can I rely on this?
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";
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)?
[*] Tested so far on: IE 6, IE 8, Safari 4, Firefox 3.6, Opera 10.5
Share Improve this question asked May 14, 2010 at 10:38 Chris LercherChris Lercher 37.8k20 gold badges102 silver badges135 bronze badges5 Answers
Reset to default 6That is the behavior according to the standard. ECMA-262 section 15.1.2.2 states that
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.
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.
Yes, you can rely on this. Go to http://www.ecma-international/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf and search for section '15.1.2.2', parseInt
why not taking a save road with
parseInt(elem1.style.top.replace(/em/, ""), 10);
Yes. You can rely on it.
parseInt("7em", 10);
will always return 7, yes. parseInt() returns the first value in the string.
And yes, parseInt is faster and easier to use than regular expressions.
And, should you use jQuery? Well it wont help you that much on the calculation or parsing in this matter, but sure your other code will probably be easier and better.
http://www.w3schools./jsref/jsref_parseInt.asp
本文标签: jqueryJavascript parseInt() with trailing charactersStack Overflow
版权声明:本文标题:jquery - Javascript: parseInt() with trailing characters - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744758036a2623580.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论