首页 > 解决方案 > js函数内部的push()返回未定义

问题描述

我对 javascript/HTML 比较陌生,我正在尝试循环请求以从不同的 URL 获取多个 JSON 对象。我的代码如下:

    <script>
    var prices = [];

    for(var i = 0; i < symbols.length; i++) {
        //prices.push("hi");
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var myObj = JSON.parse(this.responseText);
                alert(myObj["Global Quote"]["05. price"]);
                console.log(myObj["Global Quote"]["05. price"]);
                prices.push(myObj["Global Quote"]["05. price"]);
            }
        };
        var URL = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=" + symbols[i] + "&apikey=AMFNM4XBPVBLOWYF";
        xmlhttp.open("GET", URL, true);
        xmlhttp.send();
}
</script>

出于某种原因,当我这样做时,在推入 js 函数时,价格中的所有内容都是未定义的。但是,myObj 变量确实在 alert() 和 console.log() 中返回了正确的值,但由于某种原因,我无法将该值推送到我的数组中?

在此之后,我有以下代码:

<!-- TradingView Widget BEGIN-->
<script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
<script type="text/javascript">
    for (var i = 0; i < symbols.length; i++) {
        document.write('<a href="WatchList.html?symbol=');
        document.write(symbols[i]);
        document.write('"><button></button></a>');
        
        document.write('<span style="Color:white">');
        document.write(symbols[i]);
        document.write(' ');
        document.write(prices[i]);
        document.write('</span>');
        
        new TradingView.MediumWidget(

有了这个,它只是在正确打印符号后价格未定义。

标签: javascriptarraysfunction

解决方案


推荐阅读