这篇文章将为大家详细讲解有关JavaScript中Number的使用方法,文章内容质量较高,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

用法一:function

Number(value)

将一个任意类型的数据转换成数值,无法转换的则返回 NaN,转换规则类似于类型隐式转换,与 parseFloat 略有差异。

转换规则如下:

值 Value结果 ResultundefinedNaNnull0false0true1number原样输出string忽略前后空格,碰到第一个非数字字符为止,空字符串返回 0object调用内部 ToPrimitive(value, Number),如果是 Date 对象,返回从 1970年1月1日至Date的毫秒数
用法二:constructor

new Number(num)

作为一个构造器,生成一个 Number 实例, wraps num (after converting it to a number).

如:

> typeof new Number(3)'object'

既然是对象,肯定有相关的属性和方法,Number也不例外。

属性 PropertiesNumber.MAX_VALUE 表示的最大正数值

> Number.MAX_VALUE 1.7976931348623157e+308Number.MIN_VALUE 表示的最小正数值

> Number.MIN_VALUE5e-324Number.NaN 与全局 NaN 等同Number.NEGATIVE_INFINITY 与 -Infinity 等同Number.POSITIVE_INFINITY 与 Infinity 等同方法 Methods

所有原生的数值相关函数均被保存在对象原型( Number.prototype )里,可以直接调用。

Number.prototype.toFixed(fractionDigits?)

> 0.0000003.toFixed(10)'0.0000003000'Number.prototype.toPrecision(precision?)

> 1234..toPrecision(3)'1.23e+3'Number.prototype.toString(radix?)

> 15..toString(2)'1111'> 65535..toString(16)'ffff'Number.prototype.toExponential(fractionDigits?)

以上就是JavaScript中Number的使用方法,看完之后是否有所收获呢?如果想了解更多相关内容,欢迎关注亿速云行业资讯,感谢各位的阅读。