CoffeeScript - 位運算子



CoffeeScript 支援以下位運算子。假設變數A2,變數B3,則:

序號 運算子和描述 示例
1

& (按位與)

它對每個整數引數的每一位執行布林與運算。

(A & B) 為 2。
2

| (按位或)

它對每個整數引數的每一位執行布林或運算。

(A | B) 為 3。
3

^ (按位異或)

它對每個整數引數的每一位執行布林異或運算。異或意味著運算元一或運算元二為真,但不能同時為真。

(A ^ B) 為 1。
4

~ (按位非)

這是一個一元運算子,透過反轉運算元中的所有位來操作。

(~B) 為 -4。
5

<< (左移)

它將第一個運算元中的所有位向左移動第二個運算元指定的位數。新的位用零填充。將值左移一位相當於將其乘以 2,左移兩位相當於將其乘以 4,依此類推。

(A << 1) 為 4。
6

>> (右移)

二進位制右移運算子。左運算元的值向右移動右運算元指定的位數。

(A >> 1) 為 1。

示例

以下示例演示了在 CoffeeScript 中使用位運算子的方法。將此程式碼儲存在名為bitwise_example.coffee 的檔案中。

a = 2 # Bit presentation 10
b = 3 # Bit presentation 11

console.log "The result of (a & b) is "
result = a & b
console.log result

console.log "The result of (a | b) is "
result = a | b
console.log result

console.log "The result of (a ^ b) is "
result = a ^ b
console.log result

console.log "The result of (~b) is "
result = ~b
console.log result

console.log "The result of (a << b) is "
result = a << b
console.log result

console.log "The result of (a >> b) is "
result = a >> b
console.log result

開啟命令提示符並編譯 .coffee 檔案,如下所示。

c:/> coffee -c bitwise_example.coffee

編譯後,它會生成以下 JavaScript 程式碼。

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

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

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

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

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

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

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

}).call(this);

現在,再次開啟命令提示符並執行 CoffeeScript 檔案,如下所示。

c:/> coffee bitwise_example.coffee

執行後,CoffeeScript 檔案會產生以下輸出。

The result of (a & b) is
2
The result of (a | b) is
3
The result of (a ^ b) is
1
The result of (~b) is
-4
The result of (a << b) is
16
The result of (a >> b) is
0
coffeescript_operators_and_aliases.htm
廣告