CoffeeScript - 算术运算符



CoffeeScript 支持以下算术运算符。假设变量A10,变量B20,则−

序号 运算符和描述 示例
1

+ (加法)

将两个操作数相加

A + B = 30
2

− (减法)

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

A - B = -10
3

* (乘法)

将两个操作数相乘

A * B = 200
4

/ (除法)

将分子除以分母

B / A = 2
5

% (取模)

输出整数除法的余数

B % A = 0
6

++ (自增)

将整数的值增加 1

A++ = 11
7

-- (自减)

将整数的值减少 1

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_operators_and_aliases.htm
广告