CoffeeScript - 算术运算符

CoffeeScript 支持以下算术运算符。 假设变量A 的值为10,变量B 的值为20,则 −

Sr.No 运算符和说明 示例
1

+ (加法)

添加两个操作数

A + B = 30
2

− (减法)

从第一个操作数中减去第二个操作数

A - B = -10
3

* (乘法)

将两个操作数相乘

A * B = 200
4

/ (除法)

分子除以分母

B / A = 2
5

% (模数)

输出整数除法的余数

B % A = 0
6

++ (递增)

将整数值增加一

A++ = 11
7

-- (递减)

将整数值减一

A-- = 9

示例

以下示例展示了如何在 CoffeeScript 中使用算术运算符。 将此代码保存在名为 arithmetic_example.coffee 的文件中

a = 33
b = 10
c = "test"
console.log "The value of a + b = is"
result = a + b
console.log result

result = a - b
console.log "The value of a - b = is "
console.log result

console.log "The value of a / b = is"
result = a / b
console.log result

console.log "The value of a % b = is"
result = a % b
console.log result

console.log "The value of a + b + c = is"
result = a + b + c
console.log result

a = ++a
console.log "The value of ++a = is"
result = ++a
console.log result

b = --b
console.log "The value of --b = is"
result = --b
console.log result

打开命令提示符并编译.coffee 文件,如下所示。

c:\> coffee -c arithmetic_example.coffee

在编译时,它会提供以下 JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var a, b, c, result;
  a = 33;
  b = 10;
  c = "test";

  console.log("The value of a + b = is");
  result = a + b;
  console.log(result);

  result = a - b;
  console.log("The value of a - b = is ");
  console.log(result);

  console.log("The value of a / b = is");
  result = a / b;
  console.log(result);

  console.log("The value of a % b = is");
  result = a % b;
  console.log(result);

  console.log("The value of a + b + c = is");
  result = a + b + c;
  console.log(result);

  a = ++a;
  console.log("The value of ++a = is");
  result = ++a;
  console.log(result);

  b = --b;
  console.log("The value of --b = is");
  result = --b;
  console.log(result);

}).call(this);

现在,再次打开命令提示符 并运行 CoffeeScript 文件,如下所示。

c:\> coffee arithmetic_example.coffee

执行时,CoffeeScript 文件产生以下输出。

The value of a + b = is
43
The value of a - b = is
23
The value of a / b = is
3.3
The value of a % b = is
3
The value of a + b + c = is
43test
The value of ++a = is
35
The value of --b = is
8

❮ CoffeeScript - 运算符和别名