[英]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. 目前,我正在通过转换为查询Instagram而构建的香草JavaScript提要解析器来尝试使用CoffeeScript。 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.
我一直在碰壁,试图让逻辑在for循环内工作,我可以按照网络上100个示例的方式获得一个简单的for循环,但是我还没有for循环内有更多代码。 Am I approaching this completely wrong?
我要完全解决这个问题吗? The argument "results" I pass into the function is a JSON object.
我传递给函数的参数“结果”是一个JSON对象。
_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?
有小费吗?
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
. 主要区别在于
for
循环遍历results.data
每个项目。 You still had results.data[i]
in your loop, which isn't really necessary if you're iterating item-by-item. 您的循环中仍然有
results.data[i]
,如果您逐项进行迭代,这实际上不是必需的。
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 :)
你不需要它们:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.