for ... in if not null或undefined

时间:2012-12-05 19:57:33

标签: coffeescript

在我的Javascript代码中,我使用可能为null的属性处理许多json对象:

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

在将我的应用移植到coffeescript时,我使用存在运算符想出了以下快捷方式:

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

这是可接受的coffeescript吗?是否存在任何无法按预期工作的情况?

2 个答案:

答案 0 :(得分:1)

这个怎么样?

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);
  }
}

答案 1 :(得分:1)

如果我理解你的要求,那么这段代码就不会做你想要的了。

for department in store.departments ? []

看起来您正在使用与三元运算符?类似的存在运算符a?b:c。 来自coffeescript.org:

  

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

如果我想稍后使用这些名字,我会写下这样的内容:

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

你可以将它全部放在一行上,但是如果有列表理解,则变得非常难以理解。存在运算符将测试null&amp;&amp;如果它确实存在,则只返回true。

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

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

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