我目前正在尝试使用 CoffeeScript,方法是转换我为查询 Instagram 构建的普通 JavaScript 提要解析器。我一直在用头撞墙,试图让逻辑在 for 循环内部工作,我可以得到一个简单的 for 循环,按照网络上的 100 个示例来工作,但我还没有得到一个for 循环内有更多代码。我的做法完全错误吗?我传递给函数的参数“结果”是一个 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);
我不断收到错误消息,提示意外突出。有什么建议吗?
最佳答案
我会尝试这样的事情:
_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
主要区别在于 for
循环迭代 results.data
中的每个项目。您的循环中仍然有 results.data[i]
,如果您要逐项迭代,则实际上没有必要。
关于javascript - CoffeeScript 中的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15237535/