CoffeeScript - 赋值运算符



CoffeeScript 支持以下赋值运算符:

序号 运算符和描述 示例
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_operators_and_aliases.htm
广告