當使用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 - upbolate the symdate
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 } }