gpt4 book ai didi

javascript - 访问范围外的变量(javascript)

转载 作者:行者123 更新时间:2023-11-30 09:31:10 24 4
gpt4 key购买 nike

我正在尝试访问函数范围之外的变量。我正在尝试访问功能之外的价格。我是否必须等到请求完成,或者我无法访问价格?

        var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "https://api.iextrading.com/1.0/stock/aapl/quote", true);
httpRequest.send();
httpRequest.addEventListener("readystatechange", processRequest, false);

function processRequest(e) {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
response = JSON.parse(httpRequest.responseText);
console.log(response.latestPrice);
var lastPrice = response.latestPrice;
document.getElementById("StockPrice").innerHTML = lastPrice;
price = lastPrice;
}
}
document.write("outside: " + price);

最佳答案

您无权访问该函数范围之外的 price 变量。您可以做的是返回价格,然后将对该函数的调用分配给一个变量。例如:

var price = processRequest();

但是,该调用将是异步的,因此您要么必须从该函数中进行 document.write 调用,要么必须设置某种 promise 或回调以确保仅在请求完成后调用 document.write(并且 price 实际上被分配了一个值)。

这可能看起来像:

function writeToDoc (price) {
document.write("outside: " + price);
}

function processRequest(e, cb) {
// request logic
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
response = JSON.parse(httpRequest.responseText);
console.log(response.latestPrice);
var lastPrice = response.latestPrice;
document.getElementById("StockPrice").innerHTML = lastPrice;
price = lastPrice;
// Call callback function
cb(price);
}
}

httpRequest.addEventListener("readystatechange", processRequest.bind(this, writeToDoc), false);

关于javascript - 访问范围外的变量(javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46167235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com