2

In my Javascript code, I process many json objects with properties that may be null:

if (store.departments != null) {
    for(var i = 0; i < store.departments.length; i++) {
        alert(department.name);
    }
}

In porting my app to coffeescript, I came up with the following shortcut using the existential operator:

for department in store.departments ? []
    alert department.name

Is this acceptable coffeescript? Is there any scenario in which this would not work as intended?

4

2 回答 2

2

那这个呢?

if store.departments  
  alert department.name for department in store.departments

或者

alert department.name for department in store.departments if store.departments

两个语句都编译为:

var department, _i, _len, _ref;

if (store.departments) {
  _ref = store.departments;
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    department = _ref[_i];
    alert(department.name);
  }
}
于 2012-12-05T20:03:13.433 回答
1

如果我了解您的要求,则此代码不会按照您的想法进行。

for department in store.departments ? []

看起来您正在使用?类似于三元运算符的存在运算符a?b:c。来自咖啡脚本.org:

在 JavaScript 中检查变量是否存在有点困难。if (variable) ... 接近,但因零、空字符串和 false 而失败。CoffeeScript 的存在运算符 ? 除非变量为 null 或未定义,否则返回 true,这类似于 Ruby 的 nil?

如果我以后想使用这些名称,我会写如下内容:

if store.departments?
    names = (department.name for department in store.departments)

您可以将所有内容放在一行中,但是使用列表理解,这变得非常难以理解。存在运算符将测试 null && undef 并且仅在它确实存在时才返回 true。

如果你想在 coffeescript 中使用三元运算符,它就不那么简洁了:

for department in if store.departments? then store.departments else []

也许不完全是你想要的,因为它在这里非常冗长。

于 2012-12-15T23:28:23.097 回答