TypeScript - 算术运算符示例



假设变量 a 和 b 的值分别为 10 和 5。

运算符 描述 示例
+ (加法) 返回操作数的和 a + b 等于 15
- (减法) 返回值的差 a - b 等于 5
* (乘法) 返回值的积 a * b 等于 50
/ (除法) 执行除法运算并返回商 a / b 等于 2
% (模) 执行除法并返回余数 a % b 等于 0
++ (自增) 将变量的值增加 1 a++ 等于 11
-- (自减) 将变量的值减少 1 a-- 等于 9

示例

var num1:number = 10 
var num2:number = 2
var res:number = 0
 
res = num1 + num2 
console.log("Sum:        "+res); 

res = num1 - num2; 
console.log("Difference: "+res) 

res = num1*num2 
console.log("Product:    "+res) 

res = num1/num2 
console.log("Quotient:   "+res)
 
res = num1%num2 
console.log("Remainder:   "+res) 

num1++ 
console.log("Value of num1 after increment "+num1) 

num2-- 
console.log("Value of num2 after decrement "+num2)

编译后,将生成以下 JavaScript 代码。

//Generated by typescript 1.8.10
var num1 = 10;
var num2 = 2;
var res = 0;

res = num1 + num2;
console.log("Sum:        " + res);

res = num1 - num2;
console.log("Difference: " + res);

res = num1 * num2;
console.log("Product:    " + res);

res = num1 / num2;
console.log("Quotient:   " + res);

res = num1 % num2;
console.log("Remainder:   " + res);

num1++;
console.log("Value of num1 after increment " + num1);

num2--;
console.log("Value of num2 after decrement " + num2);

以上程序的输出如下所示:

Sum: 12 
Difference: 8 
Product: 20 
Quotient : 5 
Remainder: 0 
Value of num1 after increment: 11 
Value of num2 after decrement: 1
typescript_operators.htm
广告