【问题标题】:Can property path be used to define a variable in javascript属性路径可以用来在javascript中定义一个变量吗
【发布时间】:2020-01-03 12:07:43
【问题描述】:

我目前正在编写一个简短的 javascript 来调用来自 WorldWeather 在线给定坐标的 JSON 数据。目前,在我尝试更详细之前,我只是试图调用一个数据。我已经通过 Postman 运行了我的 API URL,并且数据存在。我的 javascript 是 main.js 并在我的 html 中引用。
这是我的 HTML

<!DOCTYPE html>
    <html lang="en">
   <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
    <meta charset="utf-8"/>
   <title>API TEST</title>
    <script src="https://code.jquery.com/jquery-3.4.1.js"
     integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
     crossorigin="anonymous"></script>
   <script src="main.js"></script>
  </head>
  <body>
   <div>
     <p class="wvht"></p>
   </div>
  </body>

这是我的 JS:

$.getJSON("https://api.worldweatheronline.com/premium/v1/marine.ashx? 
 key=c45390b6209242f4941174356200201&format=json&q=40.014994,-73.811646",
     function(data){
     console.log(data);

var wvht = data.weather[4].hourly[3].swellHeight_ft;

$(".wvht").append(wvht);
   }
);

我正在尝试调用膨胀高度数据 (swellheight_ft) 并使用 Google DevTools 中提供的路径来定义 wvht 变量。当我运行脚本时,我的 console.log(data) 信息很好,但也收到以下错误

Uncaught TypeError: Cannot read property '4' of undefined
at Object.success (main.js:5)
at fire (jquery-3.4.1.js:3291)
at Object.fireWith [as resolveWith] (jquery-3.4.1.js:3421)
at done (jquery-3.4.1.js:9533)
at XMLHttpRequest.<anonymous> (jquery-3.4.1.js:9785)
 main.js:5 Uncaught TypeError: Cannot read property '4' of undefined

属性“4”指的是数组。为了获取数据,我必须深入研究天气数组(7 项)和每小时数组(8 项)以获取“swellheight_ft”。我正在寻找天气数组中的第 4 天和每小时数组中的第 3 小时。

有没有更好的方法来获取所需的 swellheight_ft 数据并避免错误?

【问题讨论】:

    标签: javascript getjson


    【解决方案1】:

    这是一个愚蠢的错误,但它有时会影响我们所有人。因为您的 JSON 以:

    {"data":
    

    你的变量也被命名为data,你忘记了你需要先访问JSON的.data部分,所以只需更改

    var wvht = data.weather[4].hourly[3].swellHeight_ft;
    

    到

    var wvht = data.data.weather[4].hourly[3].swellHeight_ft;
    

    【讨论】:

    • 非常感谢。这么一个小细节,我完全喜欢它。再次感谢您!
    猜你喜欢
    • 2016-03-04
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多