操作符和 aliase
由于操作符 == 常常带来不准确的约束, 不容易达到效果, 而且跟其他语言当中意思不一致, CoffeeScript 会把 == 编译为 ===, 把 != 变异为 !==. 此外, is 编译为 ===, 而 isnt 编译为 !==.
not 可以作为 ! 的 alias 使用.
逻辑操作方面, and 编译为 &&, 而 or 编译为 ||.
在 while, if/else, switch/when 的语句当中, then 可以被用来分隔判断条件跟表达式, 这样就不用强制写换行或者分号了.
就像 YAML, on 和 yes 跟 true 是一样的, 而 off 和 no 是布尔值 false.
unless 可以认为是 if 相反的版本.
this.property 简短的写法可以用 @property.
可以用 in 判断数据在数组中是否出现, 而 of 可以探测 JavaScript 对象的属性是否存在.
为了简化数学表达式, ** 可以用来表示乘方, // 表示整除, %% 提供数学的模运算(译注: true mathematical modulo?).
完整的列表:
CoffeeScript | JavaScript |
---|---|
is | === |
isnt | !== |
not | ! |
and | && |
or | || |
true, yes, on | true |
false, no, off | false |
@, this | this |
of | in |
in | no JS equivalent |
a ** b | Math.pow(a, b) |
a // b | Math.floor(a / b) |
a %% b | (a % b + b) % b |
编译成JS:
- launch() if ignition is on
- volume = 10 if band isnt SpinalTap
- letTheWildRumpusBegin() unless answer is no
- if car.speed < limit then accelerate()
- winner = yes if pick in [47, 92, 13]
- print inspect "My name is #{@name}"
- var volume, winner;
- if (ignition === true) {
- launch();
- }
- if (band !== SpinalTap) {
- volume = 10;
- }
- if (answer !== false) {
- letTheWildRumpusBegin();
- }
- if (car.speed < limit) {
- accelerate();
- }
- if (pick === 47 || pick === 92 || pick === 13) {
- winner = true;
- }
- print(inspect("My name is " + this.name));
转载本站内容时,请务必注明来自W3xue,违者必究。