javascript - CoffeeScript 中的 for 循环

标签 javascript json coffeescript

我目前正在尝试使用 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/

相关文章:

javascript - JSON 解析以获取数组中的对象

json - 对 NGINX 服务器上托管的 Node.js Express 服务器的 cURL POST 请求返回 502 错误

javascript - 循环遍历 JSON 数组并替换为 NULL 的值

javascript - 如果所有 child 都不可见jquery隐藏 parent

javascript - 在 Rails 应用程序中组织 javascript

javascript - Laravel Gulp 未创建 js 文件夹

javascript - 当特定的 div 类发生变化时调用一个函数

javascript - 继承时原型(prototype)方法中的“this”未按预期解析

javascript - 如何为所有 XMLHTTPRequests 设置默认 header

javascript - 测试站点+实时站点分析