parseInt()应该像这样工作吗? [英] Is parseInt() supposed to work like this?

查看:66
本文介绍了parseInt()应该像这样工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写这个脚本:

alert(parseInt(123blahblahblah456));

我收到价值 123

的警报理想情况下,该函数不应该做任何事情,因为它是一个无效的整数字符串?
类似于 parseFloat()

Ideally, shouldn't the function NOT do anything since it is an invalid integer string? Similar is the case with parseFloat()

推荐答案

是的: parseInt()绝对意味着像那样工作;引用Mozilla Developer Network条目:

Yes: parseInt() is absolutely meant to work like that; to quote the Mozilla Developer Network entry:


parseInt函数将其第一个参数转换为字符串,解析它,并返回一个整数或NaN 。如果不是NaN,则返回的值将是作为指定基数(基数)中的数字的第一个参数的十进制整数表示。例如,10的基数表示从十进制数转换,8八进制,十六进制16,依此类推。对于大于10的基数,字母表中的字母表示大于9的数字。例如,对于十六进制数字(基数16),使用A到F.

The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN. If not NaN, the returned value will be the decimal integer representation of the first argument taken as a number in the specified radix (base). For example, a radix of 10 indicates to convert from a decimal number, 8 octal, 16 hexadecimal, and so on. For radices above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.

如果是parseInt遇到一个不是指定基数中的数字的字符,它会忽略它和所有后续字符,并返回解析到该点的整数值。 parseInt将数字截断为整数值。允许前导和尾随空格。

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.

似乎 parseInt()是显式地期望获取一个字符串并将采用第一个数字序列(直到遇到无效的数字字符)并将其作为radix参数中指定的任何基数的数量返回。

It seems that parseInt() is explicitly expecting to take a string and will take the first sequence of numbers (until it encounters an invalid numerical character) and return that as a number of whatever base was specified in the radix parameter.

顺便提一下,为了减少解析传递给 parseInt()的字符串时的错误,请记住使用radix参数,例如:

Incidentally, to reduce errors when parsing the strings passed to parseInt() remember to use the radix parameter, for example:

parseInt('123odod24',10); // for base-10
parseInt('123odod24',16); // for base-16

参考:

  • parseInt() at the MDC.

这篇关于parseInt()应该像这样工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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