TypeScript 数字
类似JavaScript的TypeScript支持数字值为Number对象。number对象将数字文本转换为number类的实例。number类作为一个包装器,并允许对数字文本进行操作,因为它们是对象。
语法
var var_name = new Number(value)
如果一个非数字的参数作为参数传递给Number的构造函数,则返回NaN(非数字)
下表列出了一组Number对象的属性 -
| 序号 | 属性和说明 |
|---|---|
| 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 | prototype Number对象的静态属性。使用prototype属性将新属性和方法分配给当前文档中的Number对象。 |
| 7 | constructor 返回创建此对象的实例的函数。默认情况下,这是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
示例:NaN
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
示例:prototype
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方法
Number对象仅包含作为每个对象定义一部分的默认方法。下面列出了一些常用方法:
| 序号 | 方法和说明 |
|---|---|
| 1 | toExponential() 强制数字以指数表示法显示,即使该数字在JavaScript通常使用标准表示法的范围内。 |
| 2 | toFixed() 格式化小数点右侧具有特定位数的数字。 |
| 3 | toLocaleString() 以可能根据浏览器的本地设置而变化的格式返回当前数字的string值版本。 |
| 4 | toPrecision() 定义显示数字的总位数(包括小数点左侧和右侧的数字)。负的精度将引发错误。 |
| 5 | toString() 返回数字的值的string表示形式。该函数传递基数,一个介于2和36之间的整数,指定用于表示数值的基数。 |
| 6 | valueOf() 返回数字的原始值。 |

免费 AI IDE


更多建议: