- parseInt()函数:
parseInt()函数用于解析字符串并将其转换为指定基数的整数。它需要两个参数,要解析的字符串和要使用的基数。基数是 2 到 36 之间的整数,表示数字的基数。如果parseInt函数()遇到一个字符在解析不符合规定的基数,所以会忽略字符及其后的所有字符。然后它将解析到该点的值作为整数返回。在这种情况下,允许使用前导或尾随空格。
如果函数获取第一个字符并且无法将其转换为数字,则除非基数大于 10,否则它将返回 NaN。此 NaN 值不是任何基数的有效数字,不能用于任何数学计算。
句法:
parseInt(string, radix)
- Number()函数
Number()函数用于创建原始类型的 Number 对象。它需要一个参数,即数字的值。这个值可以用一个字符串传递,Number函数会尝试将它表示为一个数字。如果参数无法转换为数字,则返回 NaN 值。此 NaN 值不是有效数字,不能用于任何数学计算。句法:
Number(valueString)
可以使用以下示例来解释这些之间的差异:
示例 1:
此示例显示parseInt()尝试将值转换为可以转换为整数的最后一个字符。尾随空格和字符被忽略,因为它们无效。另一方面, Number()函数只返回NaN 。
What is the difference between
parseInt() and Number()
GeeksforGeeks
What is the difference between
parseInt() and Number()
String is: 10 objects
Output of parseInt is:
Output of Number is:
输出:
- 点击按钮前:
- 点击按钮后:
示例 2:
此示例显示了parseInt()仅返回整数值而Number()返回所有数字(包括浮点数)的区别。
What is the difference between
parseInt() and Number()
GeeksforGeeks
What is the difference between
parseInt() and Number()
String is: 3.1415
Output of parseInt is:
Output of Number is:
输出:
- 点击按钮前:
- 点击按钮后:
示例 3:
这个例子展示了parseInt() 中基数参数的工作。传递的字符串以 2 为基数进行解析。这将返回值为 12。另一方面, Number()按原样返回字符串中的值。
What is the difference between
parseInt() and Number()
GeeksforGeeks
What is the difference between
parseInt() and Number()
String is: 1100
Output of parseInt is:
Output of Number is:
输出:
- 点击按钮前:
- 点击按钮后: