我正在尝试找到通过数组完成循环的最佳方法,该数组应该在匹配"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];这工作..。但并不理想。想法?
发布于 2015-04-17 20:40:52
只需使用多行代码,这将使代码更具可读性。
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 https://stackoverflow.com/questions/29699410
复制相似问题