include() 函数在比较数组中的值时随机工作

include() function works randomly when comparing values in array

我昨天为一个学校项目写了这段 JS 代码,一切正常。该站点显示了我想添加到对象的 key/value。虽然今天,当我重新加载服务器和站点时,所有值都是未定义的或 "muggle"。刷新了很多次页面,有时候可以,但是下次又是undefined

所以代码应该是这样的:

1.Fetch 两个 JSON 文件,一个是学生列表,另一个只是姓氏

2.Create两个数组的数据

3.Check 每个学生的姓氏,无论是否在名单上

4.Decide那个学生是纯的,半个还是麻瓜

5.Add给学生对象的值

6.Show 在网站上

我知道这与函数的调用顺序有关,在我使用 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();
      });
    });
}

并从 prepareObjects 函数中删除超时。