在 HTML 中使用 JSON 文件:Uncaught TypeError: data.forEach is not a function

新手上路,请多包涵

我浏览了网络/文档,但无法找出为什么这不起作用。

我正在尝试从 JSON 文件中插入数据(引号):{

 "quotesArray":[{
    "personName": "Albert Einstein",
    "quote": "Look deep into nature, and then you will understand everything better."
},
{
    "personName": "Stephen Hawking",
    "quote": "Look deep into nature, and then you will understand everything better."
},
{
    "personName": "Confucius",
    "quote": "Life is really simple, but we insist on making it complicated."
}]}

使用以下 JS 进入一个简单的 HTML div:

  $(document).ready(function() {
   $("#realquote").on("click", function() {
    $.getJSON('/json/quotes.json', function(data) {
     var html = " ";
       data.forEach(function(val) {
        var keys = Object.keys(val);
          html += "<div class = 'text-output'>";
            keys.forEach(function(key){
                html += val[key];

            });
               html += "</div>"
         });

       $(".realquote").html(html);
    });
   });
   });

但每次,我都会收到错误:TypeError: data.forEach is not a function”,我不知道为什么。

如果有人能将我推向正确的方向,将不胜感激!

原文由 Steven 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 823
2 个回答

data 是一个没有 .forEach 方法的常规对象。您应该遍历对象的 quotesArray 属性。

 data.quotesArray.forEach(fn);

原文由 Ram 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 data.quotesArray.forEach(.. 代替 data.forEach(..

http://js.do/code/100647

如果你想遍历数据,那么你可以使用 Object

 Object.keys(data).forEach(function (key)
{

....

});

原文由 Praveen N 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题