CoffeeScript - 比较运算符

JavaScript 支持以下比较运算符。 假设变量A 的值为10,变量B 的值为20,则 −

Sr.No 运算符和说明 示例
1

= = (等于)

检查两个操作数的值是否相等,如果相等,则条件成立。

(A == B) is not true.
2

!= (不等于)

检查两个操作数的值是否相等,如果值不相等,则条件为真。

(A != B) is true.
3

> (大于)

检查左操作数的值是否大于右操作数的值,如果是,则条件成立。

(A > B) is not true.
4

< (小于)

检查左操作数的值是否小于右操作数的值,如果是,则条件成立。

(A < B) is true.
5

>= (大于或等于)

检查左操作数的值是否大于或等于右操作数的值,如果是,则条件成立。

(A >= B) is not true.
6

<= (小于或等于)

检查左操作数的值是否小于或等于右操作数的值,如果是,则条件成立。

(A <= B) is true.

示例

以下代码展示了如何在 CoffeeScript 中使用比较运算符。 将此代码保存在名为 comparison_example.coffee 的文件中

a = 10
b = 20
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 (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

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

c:/> coffee -c comparison_example.coffee

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

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

  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 (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 comparison_example.coffee

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

The result of (a == b) is
false
The result of (a < b) is
true
The result of (a > b) is
false
The result of (a != b) is
true
The result of (a >= b) is
true
The result of (a <= b) is
false

❮ CoffeeScript - 运算符和别名