像JavaScript这样的TypeScript支持数值作为Number对象.数字对象将数字文字转换为数字类的实例. Number类充当包装器并允许操作数字文字,因为它们是对象.
var var_name = new Number(value)
如果将非数字参数作为参数传递给Number的构造函数,则返回NaN(不是a-Number)
下表列出了Number对象的一组属性 :
S.No. | Property&说明 |
---|---|
1. | MAX_VALUE JavaScript中数字的最大可能值为1.7976931348623157E + 308. |
2. | MIN_VALUE JavaScript中的数字可能具有5E-324的最小可能值. |
3. | NaN 等于非数字的值. |
4. | NEGATIVE_INFINITY 小于MIN_VALUE的值. |
5. | POSITIVE_INFINITY 一个大于MAX_VALUE. |
6. | 原型 Number对象的静态属性.使用prototype属性将新属性和方法分配给当前文档中的Number对象. |
7. | 构造函数 返回创建此对象实例的函数.默认情况下,这是Number对象. |
console.log("TypeScript Number Properties: "); console.log("Maximum value that a number variable can hold: " + Number.MAX_VALUE); console.log("The least value that a number variable can hold: " + Number.MIN_VALUE); console.log("Value of Negative Infinity: " + Number.NEGATIVE_INFINITY); console.log("Value of Negative Infinity:" + Number.POSITIVE_INFINITY);
在编译时,它将在JavaScript中生成相同的代码.
其输出如下 :
TypeScript Number Properties: Maximum value that a number variable can hold: 1.7976931348623157e+308 The least value that a number variable can hold: 5e-324 Value of Negative Infinity: -Infinity Value of Negative Infinity:Infinity
var month = 0 if( month<=0 || month >12) { month = Number.NaN console.log("Month is "+ month) } else { console.log("Value Accepted..") }
在编译时,它将在JavaScript中生成相同的代码.
其输出如下 :
Month is NaN
function employee(id:number,name:string) { this.id = id this.name = name } var emp = new employee(123,"Smith") employee.prototype.email = "smith@abc.com" console.log("Employee 's Id: "+emp.id) console.log("Employee's name: "+emp.name) console.log("Employee's Email ID: "+emp.email)
在编译时,它将生成以下JavaScript代码 :
//Generated by typescript 1.8.10 function employee(id, name) { this.id = id; this.name = name; } var emp = new employee(123, "Smith"); employee.prototype.email = "smith@abc.com"; console.log("Employee 's Id: " + emp.id); console.log("Employee's name: " + emp.name); console.log("Employee's Email ID: " + emp.email);
其输出如下 :
Employee’s Id: 123 Emaployee’s name: Smith Employee’s Email ID: smith@abc.com
Number对象仅包含作为每个对象定义一部分的默认方法.一些常用的方法列在下面 :
S.No. | 方法&说明 |
---|---|
1. | toExponential() 强制数字以指数表示法显示,即使该数字在JavaScript通常使用标准的范围内符号. |
2. | toFixed() 格式化小数点右侧具有特定位数的数字. |
3. | toLocaleString() 返回当前数字的字符串值版本,格式可能会根据浏览器的本地设置而有所不同. |
4. | toPrecision() 定义显示数字的总位数(包括小数点左边和右边的数字).负精度将引发错误. |
5. | toString() 返回数字值的字符串表示形式.该函数传递基数,一个介于2和36之间的整数,指定用于表示数值的基数. |
6. | valueOf() 返回数字的原始值. |