当使用JSON数据填充数组时遇到不一致的情况,会在控制台中显示一个空数组。
P粉438918323
2023-08-03 11:50:47
<p>我正在尝试使用AlphaVantage API获取一些数据,并且我想将某只股票支付的所有股息存储在一个数组中。我现在只尝试保存股息,但将来我希望能将股息与特定日期关联起来。<br /><br />用于检索数据的函数:</p><p><strong></strong></p>
<pre class="brush:php;toolbar:false;">async function fetchTimeSeriesDailyAdjusted (ticker) { //Fetch function to get the daily close and the dividends
const apiTimeSeriesDailyAdjusted = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=${symbol}&apikey=${apiKey}`; //Lik of the API - update the symbol
try {
const response = await fetch(apiTimeSeriesDailyAdjusted);
const data = await response.json();
const historicalDividend = []; //Array of the dividends
for (let date in data['Time Series (Daily)']) { //This for should make the code go through all the JSON
historicalDividend = entry ['7. dividend amount']; //This should store the dividend while the for loop "goes"
}
console.log(historicalDividend); //Console log to see the dividend
return historicalDividend; //Value that the function must return
} catch (error) {
console.error('Error fetching apiTimeSeriesDailyAdjusted'); //Log of the error
}
}</pre>
<p>这是我创建的函数,但正如我所看到的,可能你也看到了,它不起作用。</p>
问题在于你声明了一个名为historicalDividend的变量,并将其初始化为空数组,然后在每次迭代中重新分配整个变量给时间序列数据,这意味着你会覆盖每次的值。此外,entry未定义,我认为你可能想使用date。
为了解决所有这些问题,你应该使用map()方法,它接受一个数组,循环遍历它,并使用回调函数返回值创建一个新数组。
作为另一个提示:你应该检查响应的HTTP状态码,以确保你获得了预期的响应。
下面是修复了这两个问题的你的代码版本:
async function fetchTimeSeriesDailyAdjusted(ticker) { //Fetch function to get the daily close and the dividends const apiTimeSeriesDailyAdjusted = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=${symbol}&apikey=${apiKey}`; //Lik of the API - update the symbol try { const response = await fetch(apiTimeSeriesDailyAdjusted); // Check for HTTP response code if (!response.ok) { throw new Error( $`Fetching daily time series data failed with status code '${response.status}'` ); } const data = await response.json(); const historicalDividend = data["Time Series (Daily)"].map( (entry) => entry["7. dividend amount"] ); console.log(historicalDividend); //Console log to see the dividend return historicalDividend; //Value that the function must return } catch (error) { console.error("Error fetching apiTimeSeriesDailyAdjusted"); //Log of the error } }