JavaScript中Number()方法的两种用法


本文摘自PHP中文网,作者hzc,侵删。

JS中,调用Number()主要有两种方式,一是作为一个 function 将任意类型的数据转换成数值,二是作为一个类,通过new 生成一个数值对象。

其中第一种方式更常用。


用法一:function

1

Number(value)

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

转换规则如下:

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

用法二:constructor

1

new Number(num)

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

如:

1

2

> typeof new Number(3)

'object'

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

属性 Properties

  • Number.MAX_VALUE 表示的最大正数值

1

2

> Number.MAX_VALUE

1.7976931348623157e+308

  • Number.MIN_VALUE 表示的最小正数值

1

2

> Number.MIN_VALUE

5e-324

  • Number.NaN 与全局 NaN 等同
  • Number.NEGATIVE_INFINITY 与 -Infinity 等同
  • Number.POSITIVE_INFINITY 与 Infinity 等同

方法 Methods

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

  • Number.prototype.toFixed(fractionDigits?)

1

2

> 0.0000003.toFixed(10)

'0.0000003000'

  • Number.prototype.toPrecision(precision?)

1

2

> 1234..toPrecision(3)

'1.23e+3'

  • Number.prototype.toString(radix?)

1

2

3

4

> 15..toString(2)

'1111'

> 65535..toString(16)

'ffff'

  • Number.prototype.toExponential(fractionDigits?)

推荐教程:《JS教程》

以上就是JavaScript中Number()方法的两种用法的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

js 代码要不要加分号?

js变量的基本使用方法介绍

js输入控制只允许输入数字

js proxy 的优势以及使用场景

js屏蔽pc端访问

js闭包是什么

如何使用js实现简单日历效果

javascript和js之间有区别吗

js中相等判断===、==、object.is()的区别

js数组基础知识(总结)

更多相关阅读请进入《js》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...