摘要
Number JavaScript 对象是一个允许你处理数字值的包装对象。Number 对象使用 Number() 构造器创建。
语法
new Number(value)
参数
value- 被创建对象的数字值。
描述
Number 对象主要用于:
如果参数无法被转换为数字,则返回 NaN。
在非构造器上下文中 (如:没有 new 操作符),Number 能被用来执行类型转换。
属性
For properties available on
Number instances, see Properties of Number instances.- MAX_VALUE
- 能表示的最大正数。最大的负数是
-MAX_VALUE。 - MIN_VALUE
- 能表示的最小正数 -- 即,最接近 0 的正数 (实际上不会变成 0)。最小的负数是
-MIN_VALUE。 - NaN
- 特殊的“非数字”值。
- NEGATIVE_INFINITY
- 特殊的负无穷大值,在溢出时返回。
- POSITIVE_INFINITY
- 特殊的正无穷大值,在溢出时返回。
- prototype
- Number 对象上允许的额外属性。
方法
For methods available on
Number instances, see Methods of Number instances.isNaN- 确定传递的值是否是 NaN。
isFinite- 确定传递的值类型及本身是否是有限数。
isInteger- 确定传递的值类型是“number”,且是整数。
toInteger- 计算传递的值并将其转换为整数 (或无穷大)。
Number 实例
所有 Number 实例都继承自 Number.prototype。被修改的 Number 构造器的原型对象对全部 Number 实例都生效。
属性
-
Number.prototype.constructor -
Returns the function that created this object's instance. By default this is the
Numberobject.
方法
-
Number.prototype.toExponential() - Returns a string representing the number in exponential notation.
-
Number.prototype.toFixed() - Returns a string representing the number in fixed-point notation.
-
Number.prototype.toLocaleString() -
Returns a string with a language sensitive representation of this number. Overrides the
Object.prototype.toLocaleString()method. -
Number.prototype.toPrecision() - Returns a string representing the number to a specified precision in fixed-point or exponential notation.
-
Number.prototype.toSource() -
Returns an object literal representing the specified
Numberobject; you can use this value to create a new object. Overrides theObject.prototype.toSource()method. -
Number.prototype.toString() -
Returns a string representing the specified object in the specified radix (base). Overrides the
Object.prototype.toString()method. -
Number.prototype.valueOf() -
Returns the primitive value of the specified object. Overrides the
Object.prototype.valueOf()method.
示例
示例:使用 Number 对象给数字变量赋值
下例使用 Number 对象的属性给几个数字变量赋值:
var biggestNum = Number.MAX_VALUE; var smallestNum = Number.MIN_VALUE; var infiniteNum = Number.POSITIVE_INFINITY; var negInfiniteNum = Number.NEGATIVE_INFINITY; var notANum = Number.NaN;
示例:使用 Number 转换 Date 对象
下例使用 Number 作为函数来转换 Date 对象为数字值:
var d = new Date("December 17, 1995 03:24:00");
print(Number(d));
这将输出 "819199440000"。
浏览器兼容性
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| toSource() | 未实现 | (Yes) | 未实现 | 未实现 | 未实现 |
| Feature | Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| toSource() | 未实现 | (Yes) | 未实现 | 未实现 | 未实现 |