我昨天为学校项目写了此JS代码,一切都还好(ISH)。该站点显示了我要添加到对象的密钥/值。尽管今天,当我重新加载服务器和站点时,所有值都是未定义的或"麻瓜"。我多次刷新了页面,有时它有效,但是下次它不确定。
因此,代码应该做类似的事情:
1.取出两个JSON文件,一个是学生列表,另一个是姓氏
2.从数据中创建两个阵列
3.检查每个学生的姓氏是否在列表中
4.忠实的学生是纯净的,一半或麻瓜
5.将值添加到学生对象
6.在网站上显示
我知道这与功能的呼叫顺序有关,我使用include()方法两个检查名称是错误的。但是不幸的是,我找不到什么。这是JS代码:
//LINKS
const link = "http://petlatkea.dk/2019/hogwarts/students.json";
const bloodLink = "http://petlatkea.dk/2019/hogwarts/families.json";
//ARRAYS
let allStudents = new Array();
let halfBloods = new Array();
let pureBloods = new Array();
window.addEventListener("DOMContentLoaded", init());
function init() {
loadJSON();
}
function loadJSON() {
fetch(link)
.then(res => res.json())
.then(jsonData => {
prepareObjects(jsonData);
showStudents();
});
fetch(bloodLink)
.then(res => res.json())
.then(jsonBloodData => {
makeArrays(jsonBloodData);
});
}
// CREATE STUDENT OBJECT WITH DATA
function prepareObjects(jsonData) {
jsonData.forEach(jsonObject => {
//create new object
let student = Object.create(jsonObject);
//split name into parts
let nameParts = jsonObject.fullname.split(" ");
//assign parts to the student object
student.firstname = nameParts[0];
student.lastname = nameParts[nameParts.length - 1];
student.house = student.house;
student.imageSource =
student.lastname.toLowerCase() +
"_" +
student.firstname.slice(0, 1).toLowerCase() +
".png";
student.id = uuidv4();
student.fullname = student.fullname;
allStudents.push(student);
});
setTimeout(function(){
checkTheBlood();
}, 300);
}
// CREATE BLOOD CLASS ARRAYS
function makeArrays(data) {
for (let i = 0; i < data.half.length; i++) {
halfBloods.push(data.half[i]);
}
for (let j = 0; j < data.pure.length; j++) {
pureBloods.push(data.pure[j]);
}
}
// CHECK FOR BLOODTYPE AND ADD KEYVALUE
function checkTheBlood() {
allStudents.forEach(obj => {
if (halfBloods.includes(obj.lastname)) {
obj.bloodtype = "half";
} else if (pureBloods.includes(obj.lastname)) {
obj.bloodtype = "pure"
} else {
obj.bloodtype = "muggle"
};
})
}
这是整个代码:https://jsfiddle.net/bus5ef6p/1/
将您的loadJson函数更改为
function loadJSON() {
fetch(link)
.then(res => res.json())
.then(jsonData => {
fetch(bloodLink)
.then(res1 => res1.json())
.then(jsonBloodData => {
makeArrays(jsonBloodData);
prepareObjects(jsonData);
showStudents();
});
});
}
并从准备对象函数中删除超时。