-1

如何将变量插入地址以读取 JSON 文件。它应该是这样的。但这不起作用。第一部分有效,但这是它应该如何工作的示例。工作部分称为workingMarketCap

<!DOCTYPE html>
<html>
    <body>
    </body>

    <!--============================ SCRIPT ============================ -->
    <script>
        //Variables
        var myRequest = new XMLHttpRequest(); 
        var watchList = ["AAPL", "FB", "GOOGL", "MSFT"];
        var urlList = watchList.join(',');

        //IEX API requests open and send
        myRequest.open ('GET', `https://api.iextrading.com/1.0/stock/market/batch?symbols=${urlList}&types=quote`) //use API function "GET" to recieve data
        myRequest.send()

        //On the load of the data
        myRequest.onload = function(){
            var IEXData = JSON.parse(myRequest.responseText); //var IEXData converts JSON response to readable data for this code
            readData(IEXData, watchList); //output it into this HTML file         
        }

        /*
        =======================
            FUNCTIONS
        =======================
        */
        function readData(data, list) {
            for(var i = 0; i < 3; i++) {
                var workingMarketCap = data.AAPL.quote.marketCap;

                console.log(workingMarketCap);

                /* Does not work VVV */
                var marketCap = data.`${list[i]}`.quote.marketCap;

                console.log(marketCap);
            }
        }
    </script>
</html>
4

1 回答 1

0

您可以将功能更改为:

function readData(data, list) {
  for (var i = 0; i < list.length; i++) {
    var workingMarketCap = data.AAPL.quote.marketCap;
    console.log(workingMarketCap);

    var marketCap = data[list[i]].quote.marketCap;
    console.log(marketCap);
  }
}
于 2019-03-27T05:50:05.807 回答