所以我有一个这样定义的变量:
const myQuestions = [
{
question: "Question 1?",
answers: {
a: "A",
b: "B",
c: "The Correct One"
},
correctAnswer: "c"
},
{
question: "Question 2?",
answers: {
a: "A",
b: "B",
c: "The Correct One"
},
correctAnswer: "c"
}
];
但是我想从URL的json文件中提取变量中的内容并将其放在其中,因此我删除了该代码段并添加了以下代码:
var myQuestions;
fetch('someURLtoaJSONfile.json')
.then(response => response.json())
.then(data => {
let jsonString = JSON.stringify(data);
myQuestions = JSON.parse(jsonString);
});
,它告诉我myQuestions
未定义。但是,如果我定义myQuestions = [];
可以工作,但是当我在函数中使用console.log(myQuestions
时,它可以工作并确切地告诉我应该如何,但是当我在函数外部使用console.log(myQuestions);
时,它会告诉我数组为空...为什么?
答案 0 :(得分:0)
如果我是正确的,原因是“ then”中的代码不会立即执行,而是在您获取数据之后执行。因此,JS代码将在获取后继续执行,并执行console.log,其中myQuestions将是未定义的。
编辑
var myQuestions;
fetch('someURLtoaJSONfile.json')
.then(response => response.json())
.then(data => {
let jsonString = JSON.stringify(data);
myQuestions = JSON.parse(jsonString);
// output will be as expected because this will be
// called when data arrives
console.log(myQuestions);
});
// if done outside the function, output is undefined because
// it is called immediately after fetch is called (and fetch is
// is an asynchronous function so there is no data immediately
// after fetch because it needs time to get the data)
console.log(myQuestions);