课程表

CoffeeScript 语法

CoffeeScript 类和对象

CoffeeScript 字符串

CoffeeScript 数组

CoffeeScript 日期和时间

CoffeeScript 数学

CoffeeScript 方法

CoffeeScript 元编程

CoffeeScript jQuery

CoffeeScript 正则表达式

CoffeeScript 网络

CoffeeScript 设计模式

CoffeeScript 数据库

CoffeeScript 测试

工具箱
速查手册

CoffeeScript 存在性操作符

当前位置:免费教程 » JS/JS库/框架 » CoffeeScript

在 JavaScript 里检测一个变量的存在性有点麻烦. if (variable) ... 比较接近答案, 但是对 `0` 不成立. CoffeeScript 的存在性操作符 ? 除非是 null 或者 undefined, 否则都返回 true, 这大致是模仿 Ruby 当中的 nil?.

这也可以用在比 ||= 更安全的条件赋值当中, 有些情况你会需要处理数字跟字符串的.

CoffeeScript:
  1. solipsism = true if mind? and not world?
  2.  
  3. speed = 0
  4. speed ?= 15
  5.  
  6. footprints = yeti ? "bear"
编译成JS:
  1. var footprints, solipsism, speed;
  2.  
  3. if ((typeof mind !== "undefined" && mind !== null) && (typeof world === "undefined" || world === null)) {
  4. solipsism = true;
  5. }
  6.  
  7. speed = 0;
  8.  
  9. if (speed == null) {
  10. speed = 15;
  11. }
  12.  
  13. footprints = typeof yeti !== "undefined" && yeti !== null ? yeti : "bear";

存在性操作符 ?. 的访问器的变体可以用来吸收链式属性调用中的 null. 数据可能是 null 或者 undefined 的情况下可以用这种写法替代访问器 .. 如果所有属性都存在, 那么你会得到想要的结果, 如果链式调用有问题, 会返回 undefined 而不是抛出 TypeError.

CoffeeScript:
  1. zip = lottery.drawWinner?().address?.zipcode
编译成JS:
  1. var zip, _ref;
  2.  
  3. zip = typeof lottery.drawWinner === "function" ? (_ref = lottery.drawWinner().address) != null ? _ref.zipcode : void 0 : void 0;

吸收 null 数据的做法类似 Ruby 的 andand gem, 和 Groovy 的 safe navigation operator.

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号