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

时间:2019-03-03 12:11:31

标签: javascript arrays include fetch

我昨天为一个学校项目写了这个JS代码,一切正常。该站点显示了我想添加到对象中的键/值。尽管今天,当我重新加载服务器和站点时,所有值都未定义或“麻瓜”。我刷新了页面很多次,有时它可以工作,但是下一次再次未定义。

因此代码应执行以下操作:

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/

1 个答案:

答案 0 :(得分: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函数中删除超时。