首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >coffeescript: break for with if语句

coffeescript: break for with if语句
EN

Stack Overflow用户
提问于 2015-04-17 20:36:02
回答 1查看 368关注 0票数 0

我正在尝试找到通过数组完成循环的最佳方法,该数组应该在匹配"if“语句时返回值。

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

最理想的情况是,像这样:

代码语言:javascript
复制
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)

但是,这可以解释为:

代码语言:javascript
复制
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;
}

另一次尝试:

代码语言:javascript
复制
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)

翻译为:

代码语言:javascript
复制
_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;

这是我目前的解决方法:

代码语言:javascript
复制
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]

翻译过来就是:

代码语言:javascript
复制
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];

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

EN

回答 1

Stack Overflow用户

发布于 2015-04-17 20:40:52

只需使用多行代码,这将使代码更具可读性。

代码语言:javascript
复制
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 
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29699410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档