2

这茶匙咖啡...

    _pickInConf = (sourceConf,propsToPick...) ->
      newConfWithPickedProperties = {}
      newConfWithPickedProperties[key] = sourceConf[key] for key in Array::.concat.apply Array::,propsToPick when key in sourceConf
      newConfWithPickedProperties

...被编译成:

_pickInConf = function() {
  var key, newConfWithPickedProperties, propsToPick, sourceConf, _i, _len, _ref;
  sourceConf = arguments[0], propsToPick = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
  newConfWithPickedProperties = {};
  _ref = Array.prototype.concat.apply(Array.prototype, propsToPick);
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    key = _ref[_i];
    if (__indexOf.call(sourceConf, key) >= 0) {
      newConfWithPickedProperties[key] = sourceConf[key];
    }
  }
  return newConfWithPickedProperties;
};

...并利用:

__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

我希望 Coffeescript 编译器能够转译这个块:

when key in sourceConf

进入 :

if (key in sourceConf) {

...这就是我在JS中编码的意思...

有没有办法可以强制 Coffescript 输出这种 JS ?或者让它理解 sourceConf 是一个对象,而不是一个数组?

提前感谢您的回答!

4

2 回答 2

3

您不想of迭代in对象的键: http: //coffeescript.org/#loops(接近本节末尾)

要对此进行扩展:

for a in items when a of obj
  stuff

编译为

var a, _i, _len;

for (_i = 0, _len = items.length; _i < _len; _i++) {
  a = items[_i];
  if (a in obj) {
    stuff;

  }
}

哪个正在使用a in obj您正在寻找的

于 2013-01-30T17:39:38.683 回答
0

您想要of,而不是in检查密钥的出现: http: //coffeescript.org/#operators

于 2013-01-30T17:43:21.747 回答