TypeScript - 算术运算符示例
假设变量 a 和 b 的值分别为 10 和 5。
运算符 | 描述 | 示例 |
---|---|---|
+ (加法) | 返回操作数之和 | a +; b 为 15 |
-(减法) | 返回值的差异 | a - b 为 5 |
* (乘法) | 返回值的乘积 | a * b 为 50 |
/ (除法) | 执行除法运算并返回商 | a / b 为 2 |
% (模数) | 执行除法并返回余数 | a % b 为 0 |
++ (递增) | 将变量的值加一 | a++ 为 11 |
-- (递减) | 将变量的值减一 | 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