CoffeeScript - 赋值运算符

CoffeeScript 支持以下赋值运算符 −

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

= (简单赋值)

将右侧操作数的值赋给左侧操作数

C = A + B 会将 A + B 的值赋给 C
2

+= (添加和赋值)

它将右操作数与左操作数相加,并将结果赋给左操作数。

C += A 等同于 C = C + A
3

-= (减法和赋值)

它从左操作数中减去右操作数,并将结果赋给左操作数。

C -= A 等同于 C = C - A
4

*= (乘法和赋值)

它将右操作数与左操作数相乘,并将结果赋给左操作数。

C *= A 等同于 C = C * A
5

/= (除法和赋值)

它将左操作数与右操作数相除,并将结果赋给左操作数。

C /= A 等同于 C = C / A
6

%= (取模和赋值)

它使用两个操作数取模并将结果分配给左操作数。

C %= A 等同于 C = C % A

注意 − 相同的逻辑适用于按位运算符,因此它们将变得像 <<=, >>=, >>=, &=, |= 和 ^=。


示例

以下示例演示了 CoffeeScript 中赋值运算符的用法。 将此代码保存在名为 assignment _example.coffee 的文件中

a = 33
b = 10

console.log "The value of a after the operation (a = b) is "
result = a = b
console.log result

console.log "The value of a after the operation (a += b) is "
result = a += b
console.log result

console.log "The value of a after the operation (a -= b) is "
result = a -= b
console.log result

console.log "The value of a after the operation (a *= b) is "
result = a *= b
console.log result

console.log "The value of a after the operation (a /= b) is "
result = a /= b
console.log result

console.log "The value of a after the operation (a %= b) is "
result = a %= b
console.log result

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

c:/> coffee -c assignment _example.coffee

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

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

  console.log("The value of a after the operation (a = b) is ");
  result = a = b;
  console.log(result);

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

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

  console.log("The value of a after the operation (a *= b) is ");
  result = a *= b;
  console.log(result);

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

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

}).call(this);

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

c:/> coffee assignment _example.coffee

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

The value of a after the operation (a = b) is
10
The value of a after the operation (a += b) is
20
The value of a after the operation (a -= b) is
10
The value of a after the operation (a *= b) is
100
The value of a after the operation (a /= b) is
10
The value of a after the operation (a %= b) is
0

❮ CoffeeScript - 运算符和别名