本文介绍了JavaScript中的parseInt(string)和Number(string)有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript中的 parseInt(string) Number(string)有什么区别?

What is the difference between parseInt(string) and Number(string) in JavaScript?

推荐答案

parseInt("123hui")

返回123

Number("123hui")

返回 NaN

换句话说, parseInt()解析到第一个非数字并返回它解析的内容。 Number()想要将整个字符串转换为数字,也可以是浮动BTW。

In other words parseInt() parses up to the first non-digit and returns whatever it had parsed. Number() wants to convert the entire string into a number, which can also be a float BTW.

编辑#1:Lucero评论了可与 parseInt()一起使用的基数。就这一点而言,请参阅下面的(我不打算在此复制,应该公平分享名声......)。

EDIT #1: Lucero commented about the radix that can be used along with parseInt(). As far as that is concerned, please see THE DOCTOR's answer below (I'm not going to copy that here, the doc shall have a fair share of the fame...).

编辑#2:关于用例:这有点写已经在线之间。如果您间接想要检查给定字符串是否完全表示数值,浮点数或整数,请使用 Number() parseInt()/ parseFloat()不是那么严格,因为它们只是解析并在数值停止时停止(基数!),这使得它在你需要时很有用前面的数值如果有一个(注意 parseInt(hui)也返回 NaN )。最大的区别是使用基数 Number()不知道和 parseInt()可能间接从给定的字符串猜测(有时会导致奇怪的结果)。

EDIT #2: Regarding use cases: That's somewhat written between the lines already. Use Number() in cases where you indirectly want to check if the given string completely represents a numeric value, float or integer. parseInt()/parseFloat() aren't that strict as they just parse along and stop when the numeric value stops (radix!), which makes it useful when you need a numeric value at the front "in case there is one" (note that parseInt("hui") also returns NaN). And the biggest difference is the use of radix that Number() doesn't know of and parseInt() may indirectly guess from the given string (that can cause weird results sometimes).

这篇关于JavaScript中的parseInt(string)和Number(string)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:03