coffeescript:用if语句打破

时间:2015-04-17 12:36:02

标签: for-loop coffeescript break

我正在尝试找到完成数组循环的最佳方法,一旦“if”语句匹配,该数组应该返回一个值。

我有两个字符串,我试图遍历他们的字符并比较它们(对于排序函数)。一旦满足比较条件,我需要迭代才能中断。

最理想的是,这样的事情:

a = 'here is one'
b = 'here is two'
if a.charCodeAt(i) < b.charCodeAt(i) then -1 else 1 for i in [0...a.length] when a.charCodeAt(i) != b.charCodeAt(i)

但是,这转化为:

if (a.charCodeAt(i) < b.charCodeAt(i)) {
  return -1;
} else {
  _results = [];
  for (i = _i = 0, _ref = a.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
    if (a.charCodeAt(i) !== b.charCodeAt(i)) {
      _results.push(1);
    }
  }
  return _results;
}

另一次尝试:

pos = (if a.charCodeAt(i) < b.charCodeAt(i) then -1 else 1) for i in [0...a.length] when a.charCodeAt(i) != b.charCodeAt(i)

转换为:

_results = [];
for (i = _i = 0, _ref = a.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  if (a.charCodeAt(i) !== b.charCodeAt(i)) {
    _results.push(pos = (a.charCodeAt(i) < b.charCodeAt(i) ? -1 : 1));
  }
}
return _results;

这是我目前的解决方法:

a = 'here is one'
b = 'here is two'
return (for i in [0...a.length]
  do ->
    if a.charCodeAt(i) < b.charCodeAt(i) then -1 else 1
)[0]

转换为:

return ((function() {
  var _i, _ref, _results;
  _results = [];
  for (index = _i = 0, _ref = a['dep'].length; 0 <= _ref ? _i < _ref : _i > _ref; index = 0 <= _ref ? ++_i : --_i) {
    _results.push((function() {
      if (a['dep'].charCodeAt(index) < b['dep'].charCodeAt(index)) {
        return -1;
      } else {
        return 1;
      }
    })());
  }
  return _results;
})())[0];

这份工作......但不理想。 想法?

1 个答案:

答案 0 :(得分:2)

只需使用多行,无论如何都会让它更具可读性。

a = 'here is one'
b = 'here is two'
[x] = for i in [0...a.length] when a.charCodeAt(i) != b.charCodeAt(i)
    if a.charCodeAt(i) < b.charCodeAt(i) then -1 else 1