属性路径可以用来定义javascript中的变量吗

Can property path be used to define a variable in javascript

我目前正在写一个简短的 javascript 以从 WorldWeather 在线调用给定坐标的 JSON 数据。目前,我只是试图在尝试变得更详细之前调用一个数据。我有 运行 我的 API URL 通过 Postman 并且数据存在。我的 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 数据并避免错误?

这是一个愚蠢的错误,但有时会让我们陷入困境。因为您的 JSON 开头为:

{"data":

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

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

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