James Billings
James Billings

Reputation: 448

for loops in coffee script

I'm trying my hand at CoffeeScript at the moment by converting a vanilla JavaScript feed parser I built to query Instagram. I've been hitting my head against the wall trying to get the logic to work inside of a for loop, I can get a simple for loop to work as per the 100's of examples on the web but I've yet to get one with more code inside the for loop. Am I approaching this completely wrong? The argument "results" I pass into the function is a JSON object.

_feed: (results) ->
    images = results.length
    for img in images
      a = document.createElement('a');
      a.href = results.data[i].images.standard_resolution.url;
      img = document.createElement("img");
      img.src = results.data[i].images.low_resolution.url;
      a.appendChild(img);
      document.getElementsByTagName('body')[0].appendChild(a);

I keep getting errors saying unexpected outdent. Any tips?

Upvotes: 0

Views: 200

Answers (2)

Blender
Blender

Reputation: 298126

I would try something like this instead:

_feed: (results) ->
    for result in results.data
        a = document.createElement 'a'
        a.href = result.images.standard_resolution.url

        img = document.createElement 'img'
        img.src = result.images.low_resolution.url

        a.appendChild img
        document.body.appendChild a

The main difference is that the for loop iterates over each item in results.data. You still had results.data[i] in your loop, which isn't really necessary if you're iterating item-by-item.

Upvotes: 3

Andrew Mao
Andrew Mao

Reputation: 36900

Make sure that you are using an editor that uses soft tabs (spaces) instead of hard tabs; and check that all the lines are indented as you expect: two spaces for the first two lines, four spaces for the other lines; etc. Otherwise, you will definitely get those errors mixing tabs and spaces.

I also see that there is a random backtick at the very end of your code; is that in the actual code or did you just copy it here?

Also, start ignoring semicolons; you don't need them :)

Upvotes: 0

Related Questions