在JavaScript中,parseInt(字符串)和Number(字符串)之间的区别是什么?
当前回答
@sjngm回答的附录: 它们都忽略空白: Var foo = " 3 ";console.log(方法(foo));/ / 3 console.log(数量(foo));/ / 3
这并不完全正确。作为sggnm写parseInt解析字符串到第一个数字。这是真的。但问题是当你想解析用空格分隔的数字时。“345”。在这种情况下,parseInt("12 345")将返回12而不是12345。 因此,为了避免这种情况,必须在解析数字之前删除空白。 我的解决方案是:
var number=parseInt("12 345".replace(/\s+/g, ''),10);
注意,我在parseInt()函数中使用了一个额外的东西。parseInt("string",10)将数字设置为十进制格式。如果你解析像“08”这样的字符串,你会得到0,因为8不是八进制数。解释在这里
其他回答
parseInt(string)将包含非数字字符的字符串转换为数字,只要字符串以数字字符开头
'10px' => 10
如果字符串包含任何非数字字符,Number(string)将返回NaN
'10px' => NaN
parseInt函数允许您为输入字符串指定基数,并且限制为整数值。
parseInt('Z', 36) === 35
作为函数调用的Number构造函数将使用语法解析字符串,并限制为以10为底和以16为底。
StringNumericLiteral ::: StrWhiteSpaceopt StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt StrWhiteSpace ::: StrWhiteSpaceChar StrWhiteSpaceopt StrWhiteSpaceChar ::: WhiteSpace LineTerminator StrNumericLiteral ::: StrDecimalLiteral HexIntegerLiteral StrDecimalLiteral ::: StrUnsignedDecimalLiteral + StrUnsignedDecimalLiteral - StrUnsignedDecimalLiteral StrUnsignedDecimalLiteral ::: Infinity DecimalDigits . DecimalDigitsopt ExponentPartopt . DecimalDigits ExponentPartopt DecimalDigits ExponentPartopt DecimalDigits ::: DecimalDigit DecimalDigits DecimalDigit DecimalDigit ::: one of 0 1 2 3 4 5 6 7 8 9 ExponentPart ::: ExponentIndicator SignedInteger ExponentIndicator ::: one of e E SignedInteger ::: DecimalDigits + DecimalDigits - DecimalDigits HexIntegerLiteral ::: 0x HexDigit 0X HexDigit HexIntegerLiteral HexDigit HexDigit ::: one of 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F
@sjngm回答的附录:
它们都忽略空白:
var foo = " 3 ";
console.log(parseInt(foo)); // 3
console.log(Number(foo)); // 3
@sjngm回答的附录: 它们都忽略空白: Var foo = " 3 ";console.log(方法(foo));/ / 3 console.log(数量(foo));/ / 3
这并不完全正确。作为sggnm写parseInt解析字符串到第一个数字。这是真的。但问题是当你想解析用空格分隔的数字时。“345”。在这种情况下,parseInt("12 345")将返回12而不是12345。 因此,为了避免这种情况,必须在解析数字之前删除空白。 我的解决方案是:
var number=parseInt("12 345".replace(/\s+/g, ''),10);
注意,我在parseInt()函数中使用了一个额外的东西。parseInt("string",10)将数字设置为十进制格式。如果你解析像“08”这样的字符串,你会得到0,因为8不是八进制数。解释在这里
第一个函数有两个参数:
parseInt(string, radix)
radix参数用于指定要使用的数字系统,例如,基数16(十六进制)表示字符串中的数字应该从十六进制数解析为十进制数。
如果省略了radix参数,JavaScript假设如下:
如果字符串以“0x”开头,则 基数是16(十六进制) 如果字符串以“0”开头,则 基数是8(八进制)。这个特性 被弃用 如果字符串以任何其他开头 值,基数为10(十进制)
你提到的另一个函数只有一个参数:
Number(object)
Number()函数的作用是:将对象参数转换为表示对象值的数字。
如果该值不能转换为合法的数字,则返回NaN。