簡體   English   中英

Javascript 訪問數組並顯示其項目

[英]Javascript accessing array and displaying its items

我在這里有一個 JSON 格式的數據: https://xnia140ixg.execute-api.us-east-1.amazonaws.com/Stage1/currencies

我想在圖表中顯示它。 我寫了那個代碼

let CurrData = [];
        let res = axios.get('https://xnia140ixg.execute-api.us-east-1.amazonaws.com/Stage1/currencies').then(Response => {
            let data = Response.data.Items
            console.log(data);

            CurrData.push(data);
        });

我試圖做的是將該數據推送到我可以在此方法之外訪問的新數組中,然后遍歷每個項目。 但我無法做到這一點。 這就是我現在得到的大批

我現在要做的是訪問 Price 和 PriceTimeStamp 並將其放入 plotly.js object 中,如下所示:

CurrData.forEach(Curr => {
            //Specify how chart should be drawn
            let trace = {
                x: Curr.Price,
                y: Curr.PriceTimeStamp,
                mode: 'line',
                name: Curr.Currency,
                marker: {
                    color: 'rgb(219, 64, 82)',
                    size: 12
                }
            };

我應該改變什么?

你應該寫

CurrData = data;

代替

CurrData.push(data);

你正在將一個數組推入一個數組。

如果您在獲取后調用循環,您將不會得到任何東西。 在 setTimeout 或異步 function 內運行。 想想你的 scope。 您調用仍在獲取的數據,因此 Curr 未定義,但如果您處於異步 function 中,那么當您調用循環時,它將在完成過程后呈現。

async function getData(){
    return await axios.get('https://xnia140ixg.execute-api.us-east-1.amazonaws.com/Stage1/currencies').then(Response => {
        return Response.data.Items
    });
}

// is going to work, after it finishes fetching
async function buildTrace(){
    await getData().then(curr => {
        return {
            x: curr['Price'],
            y: curr['PriceTimeStamp'],
            mode: 'line',
            name: curr['Currency'],
            marker: {
                color: 'rgb(219, 64, 82)',
                size: 12
            }
        };
    })
}

// your data is stil fetching, no results == undefined
function buildTrace(){
    await getData().then(curr => {
        return ...
    })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM