【问题标题】:Javascript accessing array and displaying its itemsJavascript访问数组并显示其项目
【发布时间】:2021-03-03 20:00:30
【问题描述】:

我这里有一个 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 对象中,如下所示:

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
                }
            };

我应该改变什么?

【问题讨论】:

    标签: javascript arrays function methods


    【解决方案1】:

    你应该写

    CurrData = data;
    

    而不是

    CurrData.push(data);
    

    你正在将一个数组推入一个数组中。

    【讨论】:

      【解决方案2】:

      如果你在获取后调用你的循环,你将不会得到任何东西。 在 setTimeout 或异步函数中运行。想想你的范围。您对仍在获取的数据的调用,因此 Curr 是未定义的,但是如果您在异步函数中,那么当您调用循环时,它将在完成过程时呈现。

      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 ...
          })
      }
      

      【讨论】:

        猜你喜欢
        • 2015-08-23
        • 2015-04-13
        • 2020-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-11
        • 1970-01-01
        • 2020-07-23
        相关资源
        最近更新 更多