在HTML中使用JSON文件:Uncaught TypeError:data.forEach不是一个函数。

4

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

我正在尝试从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不是一个函数”,我无法弄清原因。
如果有人能指导我正确的方向,将不胜感激!
3个回答

5

data是一个普通的对象,没有.forEach方法。你需要遍历这个对象的quotesArray属性。

data.quotesArray.forEach(fn);

1

你需要使用data.quotesArray来实际访问你想要迭代的数组。

回调中的data保存了从JSON文件返回的对象。由于普通的JavaScript对象没有.forEach方法,因此你会收到一个错误。


1

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

http://js.do/code/100647

如果您想遍历数据,则可以使用Object
Object.keys(data).forEach(function (key)
{

....

});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接