javascript - 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(
有了这个,它只是在正确打印符号后价格未定义。
解决方案
推荐阅读
- android - 如何在屏幕旋转时保持 recyclerView 的滚动位置
- typescript - TypeScript 中的 `{}` 类型和 `object` 类型有什么区别?
- mysql - 如何解决问题:zone.js:3243 POST http://localhost:4200/login 404(未找到)
- java - StaxEventItemReader 中的 ClassCastException
- powershell - 将数字转换为货币
- mocking - 当我尝试模拟它时,Sphinx / ReadTheDocs 仍然尝试构建一个模块
- android - Flutter Hot Reload 按钮未激活
- express - 如何从用户的当前(“位置”)找到附近的商店提供纬度和经度
- python - 针对从末尾开始的一组列表的逻辑
- entity-framework-core - 一个 API 调用来检索模型中的所有项目