很明显,我对 Javascript 很陌生。对于我正在构建的应用程序,我需要将从提取请求中获取的数据保存到一个变量中,理想情况下我可以在我的函数之外访问该变量。对此的任何了解都将不胜感激。
这是我的代码:
function generateNewQuote() {
fetch('https://api.whatdoestrumpthink.com/api/v1/quotes/random')
.then(response => response.json())
.then(data => {
const newMes = data.message;
console.log(newMes );
});
}
我需要将我的 newMes 变量的值放入一个我可以在全局范围内指定的变量,或者另一种方法来访问位于全局范围内的 generateNewQuote 函数内的 newMes 变量。
最佳答案
更改变量范围。
let newMes = [];
function generateNewQuote() {
newMes = [];
fetch('https://api.whatdoestrumpthink.com/api/v1/quotes/random')
.then(response => response.json())
.then(data => {
newMes = data;
console.log(newMes.message );
});
}
关于javascript - 如何将从 JavaScript 中的获取请求中获取的数据保存到函数外部的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62818314/