数组中的对象未定义

objects in the array are undefined

为什么数组未定义

我的问题是如何显示结果数组中的对象。我试过 console.log(data.results[0].bodyColor) 但出现错误。当我尝试 (data.results) 时,我变得不确定。当我尝试 (data.results[0]) 时,它给出了错误消息的响应。为什么我可以在控制台上看到数组未定义。 [这是控制台,所以我如何打印出 AirBagLocFront 的值][1]

<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Untitled Document</title>
</head>

<body>
    <h2> Vehicle API</h2>
    <div id="div"></div>
    <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
    <!--Jquery CDN-->
    <script>
        $.ajax({
            url: "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/",
            type: "POST",
            cache: true,

            data: {
                format: "json",
                data: "WBAPK5C52AA599960;"
            },
            dataType: "json",

            success: function(data) {

                console.log(data.results[0].AirBagLocFront);

            }
        });
    </script>
</body>

</html>

您的代码中有错字。你想要 Results,而不是 results。此外,Results 是一个包含单个对象的数组。您可以使用 for...in 循环很容易地遍历整个数据结构。这是一个工作片段:

$.ajax({
  url: "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/",
  type: "POST",
  cache: true,
  data: {
    format: "json",
    data: "WBAPK5C52AA599960;"
  },
  dataType: "json",
  success: function(data) {
    var res = data.Results[0];
    for (var prop in res) {
      if (res.hasOwnProperty(prop)) {
        console.log(prop + ' - ' + (res[prop] ? res[prop] : 'N/A'));
      }
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Untitled Document</title>
</head>

<body>
    <h2> Vehicle API</h2>
    <div id="div"></div>
    <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
    <!--Jquery CDN-->
    <script>
        $.ajax({
            url: "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/",
            type: "POST",
            cache: true,

            data: {
                format: "json",
                data: "WBAPK5C52AA599960;"
            },
            dataType: "json",

            success: function(data) {

                console.log(data['Results'][0]['BodyClass']);

            }
        }):
    </script>
</body>

</html>

这有效我用来访问嵌套对象的语法不正确。感谢大家。