Vikram
Vikram

Reputation: 3351

Loop within loop coffeescript

In coffeescript how can I have for loop withing a for loop

I am trying with following code but its not working

scale = filenames.length
for key, filename in filenames
    x = key
    for i in [x...scale]
        alert(i)

where filenames is an array of filenames

when I try following, it works

for key, filename in filenames
    x = key
    for i in [0...scale]
        alert(i)

Upvotes: 1

Views: 57

Answers (1)

ROAL
ROAL

Reputation: 1779

In Coffeescript, the first argument passed to for ... in gets populated with the actual value, second, optional parameter, is for the index.

x = key is also not necessary in this code, you can directly refer to key.

The result should be as follows:

filenames = ['One.txt', 'Two.txt', 'Three.txt'] # a dummy array for testing purposes
scale = filenames.length

# now the actual loop
for filename, key in filenames
    for i in [key...scale]
        alert i

See second example in CoffeeScript - Loops and Comprehensions

Upvotes: 3

Related Questions