如何解决通过函数 ~ Javascript
const main_db = {
"concepts": []
}
function loadJson() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
updateLocalDbObject(this.responseText);
}
};
xhttp.open("GET","main_db.json",true);
xhttp.send();
}
function updateLocalDbObject(jsonObject)
{
const json = JSON.parse(jsonObject);
for(let i=2; i<json.concepts.length; i++)
{
main_db.concepts.push(createObject(jsonObject,json.concepts[i]));
}
//why does this return the object.
console.log(main_db.concepts[0]);
}
function createObject(jsonObject,objectValues){
const json = JSON.parse(jsonObject);
let newObject = {};
json.concepts[0].forEach((key,i) => {
Object.assign(newObject,{[key]: objectValues[i]});
});
// console.log(newObject);
return newObject;
}
//why does this return undefined?
console.log(main_db.concepts[0]);
我知道这与 XMLRequest 异步有关,但我不知道如何使用本地对象更新全局数组,以及如何从 loadJson 函数之外的其他函数引用全局数组的对象。
>版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。