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

Ste*_*ven 4 html javascript jquery json

我浏览了 web/docs,但找不到为什么这不起作用。

我正在尝试从 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."
}]}
Run Code Online (Sandbox Code Playgroud)

使用以下 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);
    });
   });          
   });
Run Code Online (Sandbox Code Playgroud)

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

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

und*_*ned 5

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

data.quotesArray.forEach(fn);
Run Code Online (Sandbox Code Playgroud)