Noob问题。我正在尝试用范围编写for循环。例如,这就是我想用JavaScript生成的东西:
var i, a, j, b, len = arr.length;
for (i = 0; i < len - 1; i++) {
a = arr[i];
for (j = i + 1; i < len; j++) {
b = arr[j];
doSomething(a, b);
}
}
我到目前为止最接近的是以下,但
CoffeeScript的:
for a, i in a[0...a.length-1]
for b, j in a[i+1...a.length]
doSomething a, b
生成的代码:
var a, b, i, j, _i, _j, _len, _len1, _ref, _ref1;
_ref = a.slice(0, a.length - 1);
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
a = _ref[i];
_ref1 = a.slice(i + 1, a.length);
for (j = _j = 0, _len1 = _ref1.length; _j < _len1; j = ++_j) {
b = _ref1[j];
doSomething(a, b);
}
}
(How)可以用CoffeeScript表示吗?
答案 0 :(得分:9)
基本上,将您的第一个JS代码转录到CS:
len = arr.length
for i in [0...len - 1] by 1
a = arr[i]
for j in [i + 1...len] by 1
b = arr[j]
doSomething a, b
答案 1 :(得分:1)
似乎避免额外变量的唯一方法是使用while
循环http://js2.coffee
i = 0
len = arr.length
while i < len - 1
a = arr[i]
j = i + 1
while j < len
b = arr[j]
doSomething a, b
j++
i++
或者可读性稍差:
i = 0; len = arr.length - 1
while i < len
a = arr[i++]; j = i
while j <= len
doSomething a, arr[j++]
答案 2 :(得分:0)
使用CoffeeScript 2
,您可以
for value, index in [1...10]
来源:https://coffeescript-cookbook.github.io/chapters/syntax/for_loops