CoffeeScript 存在性操作符
在 JavaScript 里检测一个变量的存在性有点麻烦. if (variable) ... 比较接近答案, 但是对 `0` 不成立. CoffeeScript 的存在性操作符 ? 除非是 null 或者 undefined, 否则都返回 true, 这大致是模仿 Ruby 当中的 nil?.
这也可以用在比 ||= 更安全的条件赋值当中, 有些情况你会需要处理数字跟字符串的.
CoffeeScript:编译成JS:
- solipsism = true if mind? and not world?
- speed = 0
- speed ?= 15
- footprints = yeti ? "bear"
- var footprints, solipsism, speed;
- if ((typeof mind !== "undefined" && mind !== null) && (typeof world === "undefined" || world === null)) {
- solipsism = true;
- }
- speed = 0;
- if (speed == null) {
- speed = 15;
- }
- footprints = typeof yeti !== "undefined" && yeti !== null ? yeti : "bear";
存在性操作符 ?. 的访问器的变体可以用来吸收链式属性调用中的 null. 数据可能是 null 或者 undefined 的情况下可以用这种写法替代访问器 .. 如果所有属性都存在, 那么你会得到想要的结果, 如果链式调用有问题, 会返回 undefined 而不是抛出 TypeError.
CoffeeScript:编译成JS:
- zip = lottery.drawWinner?().address?.zipcode
- var zip, _ref;
- 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,违者必究。