CoffeeScript - 逻辑运算符



CoffeeScript 支持以下逻辑运算符。假设变量A持有,且变量B持有,那么 -

序号 运算符和说明 示例
1

&& (逻辑与)

如果两个操作数都是真,那么条件为真。

(A && B) 为假。
2

|| (逻辑或)

如果任何两个操作数为真,那么条件为真。

(A || B) 为真。
3

! (逻辑非)

逆转其操作数的逻辑状态。如果一个条件为真,那么逻辑非运算符会将其变为假。

! (A && B) 为真。

示例

以下是演示在 coffeeScript 中使用逻辑运算符的示例。将此代码保存在名为 logical_example.coffee 的文件中。

a = true
b = false

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

打开命令提示符,并按照以下方式编译 .coffee 文件。

c:\> coffee -c logical_example.coffee

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

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

  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);

}).call(this);

现在,重新打开命令提示符,并按照以下方式运行 CoffeeScript 文件。

c:\> coffee logical_example.coffee

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

The result of (a && b) is
false
The result of (a || b) is
true
The result of !(a && b) is
true
coffeescript_operators_and_aliases.htm
广告
© . All rights reserved.