咖啡脚本测试,如果没有定义

pet*_*oke 14 coffeescript

根据咖啡脚本网站

console.log(s) if s?
Run Code Online (Sandbox Code Playgroud)

应该生成

if (typeof s !== "undefined" && s !== null) {
    console.log(s);
}
Run Code Online (Sandbox Code Playgroud)

但是我的浏览器中出现的是什么

  if (s != null) {
      return console.log(s);
  }
Run Code Online (Sandbox Code Playgroud)

使用coffee-script-source(1.6.2),coffee-rails(3.2.2),rails-backbone(0.7.2),rails(3.2.13)

这是我的咖啡脚本功能.任何想法为什么我没有得到什么咖啡脚本网站说我应该?

window.p = (s) ->
    console.log(s) if s?
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 31

如果你只是说:

console.log(s) if s?
Run Code Online (Sandbox Code Playgroud)

那么你确实会得到你期待的JavaScript(演示):

if (typeof s !== "undefined" && s !== null) {
  console.log(s);
}
Run Code Online (Sandbox Code Playgroud)

但是,如果s是已知变量,例如:

f = (s) -> console.log(s) if s?
Run Code Online (Sandbox Code Playgroud)

然后你会得到(演示):

if (s != null) {
  //...
}
Run Code Online (Sandbox Code Playgroud)

为了s?测试.

为什么差异呢?在第一种情况下,CoffeeScript无法保证s在任何地方都存在变量,因此必须进行typeof s检查以避免ReferenceError异常.

但是,如果s已知存在,因为它是一个函数参数或已被指定为局部变量(以便CoffeeScript将生成一个var s),那么您不需要typeof s检查,因为在这种情况下,您不能获得ReferenceError.

这让我们与s !== null对手相提并论s != null.下降到非严格不等式(s != null),您可以检查是否sundefinednull有一个比较.当您检查时typeof s !== "undefined",您将undefined测试包装在"有s变量"检查中,并且s !== null您需要检查所有需要的严格测试null.

  • 通过Javascript(Ecmascript)标准`undefined`和`null`是`==`相等,所以`s == null`是一个古老而完善的用法.但许多lint标准反对使用`==`.如果编译的coffeescript必须得到lint批准,那么这就是你要解决的问题之一. (2认同)