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
廣告

© . All rights reserved.