Number(...)和parseFloat(...)之间有什么区别 [英] What is the difference between Number(...) and parseFloat(...)

查看:250
本文介绍了Number(...)和parseFloat(...)之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前已经询问过什么是JavaScript中的parseInt(字符串)和数字(字符串)

但答案主要集中在 radix 以及 parseInt 取一个字符串,如123htg并将其转换为 123

But the answers basically focused on the radix and the ability of parseInt to take a string like "123htg" and turn it into 123.

我在这里问的是, Number(...) parseFloat的回报之间是否有任何重大差异(...)当你传递实际数字字符串时根本没有基数。

What I am asking here is if there is any big difference between the returns of Number(...) and parseFloat(...) when you pass it an actual number string with no radix at all.

推荐答案

没有。两者都将导致内部 ToNumber(字符串) 正在调用函数。

No. Both will result in the internal ToNumber(string) function being called.

来自 ES5第15.7.1节(作为函数调用的数字构造函数):

From ES5 section 15.7.1 (The Number Constructor Called as a Function):


Number 作为函数而不是构造函数调用,它执行类型转换...

When Number is called as a function rather than as a constructor, it performs a type conversion...

返回计算的Number值(不是Number对象) by ToNumber(value)如果提供了值,则返回 +0

Returns a Number value (not a Number object) computed by ToNumber(value) if value was supplied, else returns +0.

来自 ES5第15.1.2.3节(parseFloat(string)):

From ES5 section 15.1.2.3 (parseFloat (string)):


...
如果 trimmedString 也没有 trimmedString 的任何前缀满足 StrDecimalLiteral 的语法(见9.3.1)
...

... If neither trimmedString nor any prefix of trimmedString satisfies the syntax of a StrDecimalLiteral (see 9.3.1) ...

9.3.1 是标题为ToNumber应用于字符串类型的部分,是第一个引用所指的是 ToNumber(值)

And 9.3.1 is the section titled "ToNumber Applied to the String Type", which is what the first quote is referring to when it says ToNumber(value).

更新(见评论)

通过调用 Number 构造函数使用 new 运算符,您将获得 Number 对象的实例,而不是数字文字。例如:

By calling the Number constructor with the new operator, you will get an instance of the Number object, rather than a numeric literal. For example:

typeof new Number(10); //object
typeof Number(10); //number

这是在 15.7.2节(数字构造函数):

This is defined in section 15.7.2 (The Number Constructor):


何时 Number 作为 new 表达式的一部分被调用它是一个构造函数:它初始化新创建的对象。

When Number is called as part of a new expression it is a constructor: it initialises the newly created object.

这篇关于Number(...)和parseFloat(...)之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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