Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

Why does Javascript parseInt('0x4A') return the same as parseInt('0x4Avv')?

Why does Javascript parseInt('0x4Avv') return the same as parseInt('0x4A') I was counting on parseInt('0x4Avv') to return NaN.

Is there anyway to make it behave as such?

Even weird strings 'work', e.g: parseInt('0x4Av--9-0-90v') yields the same result as parseInt('0x4A')

Observed in all browsers....

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is an excerpt from the MDN parseInt documentation

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

There isn't a built in way to make it behave otherwise, but you could conceivably write your own int parsing function using regex that could be more strict.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...