CoffeeScript - 逻辑运算符的别名



下表显示了一些逻辑运算符的别名。假设变量Xtrue,变量Yfalse

运算符 别名 示例
&& (逻辑与) and X and Y 的结果为 false
|| (逻辑或) or X or Y 的结果为 true
! (非 x) not not X 的结果为 false

示例

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

a = true
b = false

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

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

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

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

c:\> coffee -c logical_aliases.coffee

编译后,它会生成以下 JavaScript 代码。

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

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

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

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

}).call(this);

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

c:\> coffee logical_aliases.coffee

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

The result of (a and b) is
false
The result of (a or b) is
true
The result of not(a and b) is
true
coffeescript_operators_and_aliases.htm
广告