设置属性后删除对象

时间:2019-02-22 16:57:55

标签: javascript class object

我有一个名为“学校”的类,其中包括对“小学生”对象执行操作的方法,这是该类的属性。

我还有三种HTML表单,可让您添加学生,删除学生和为学生设置特定属性。

除此条件外,它们都起作用:如果我设置了一个瞳孔属性,然后尝试删除同一瞳孔,则它不起作用。此错误已记录到控制台:

  

未捕获的TypeError:无法读取未定义的属性“ id”       在School.findPupilProperty((索引):59)       在HTMLFormElement.delPupil((index:195)

class School {
  constructor(name, level, pupils) {
    this.name = name;
    this.level = level;
    this.pupils = pupils;
  }
  getPupil(name) {
    name = this.nameUpperCase(name);
    let pupil = this.pupils.find(function(obj) {
      return obj.name === name;
    });
    return pupil;
  }
  getPupilsByProperty(property, value) {
    let pupilArray = this.pupils.filter(function(obj) {
      return obj.property === value;
    });
    return pupilArray;
  }
  findPupilProperty(property, value, find) {
    if (property === 'name') {
      value = this.nameUpperCase(value);
    }
    let desired_pupil = this.pupils.find(function(obj) {
      return obj[property] === value;
    });
    return desired_pupil[find];
  }
  generateNewPupilID() {
    for (let i = 0; i < this.pupils.length; i++) {
      if (i === this.pupils.length - 1) {
        return this.pupils[i].id + 1;
      }
    }
  }
  addPupil(name, age, grades = [], attendance = 0) {
   // name = this.nameUpperCase(name);
    let id = this.generateNewPupilID();
    this.pupils.push({
      id: id,
      name: name,
      age: age,
      grades: grades,
      attendance: attendance
    });
  }
  deletePupil(name) {
    name = this.nameUpperCase(name);
    let pupil = this.pupils.find(function(obj) {
      return obj.name === name;
    });
    let index = this.pupils.findIndex(function(obj) {
      return obj.name === name;
    });
    this.pupils.splice(index, 1);
  }
  nameUpperCase(name) {
  	name = name.split(' ');
    let first_name_arr = name[0].split('');
    let last_name_arr  = name[1].split('');
    for(let i = 0; i < first_name_arr.length; i++) {
    	if(i === 0) {
      	first_name_arr[0] = first_name_arr[0].toUpperCase();
      } else {
      	first_name_arr[i] = first_name_arr[i].toLowerCase();
      }
    }
    for(let x = 0; x < last_name_arr.length; x++) {
    	if(x === 0) {
      	last_name_arr[0] = last_name_arr[0].toUpperCase();
      } else {
      	last_name_arr[x] = last_name_arr[x].toLowerCase();
      }
    }
    let strname =  first_name_arr.join('') + ' ' + last_name_arr.join('');
    return strname;
 }
  
  setPupilProperty(name, property, value) {
    name = this.nameUpperCase(name);
    let pupil = this.pupils.find(function(obj) {
      return obj.name === name;
    });
    property = property.toLowerCase();
    pupil[property] = value;
  }
  getGradesByPupil(name, subject) {
    this.pupils.forEach(function(obj) {
      if (obj.name === name) {
        if (!subject) {
          return obj.grades;
        } else {
          return obj.grades.subject;
        }
      }
    });
  }
}

let pupils = [{
    id: 1,
    name: 'John Doe',
    age: 17,
    grades: {
      'English': 9,
      'Maths': 9,
      'Sociology': 'A*'
    },
    attendance: 12
  },
  {
    id: 2,
    name: 'Jane Doe',
    age: 17,
    grades: {
      'English': 7,
      'Maths': 6,
      'Sociology': 'B'
    },
    attendance: 92
  }
];

const school = new School('somethingschool', 'high', pupils);

function displayPupil(obj) {
  document.getElementById('pupils').innerHTML +=
    `
  <div id=pupil-${obj.id}>
  <h3>${obj.name}</h3>
  <p>ID: ${obj.id}</p>
  <p>Age: ${obj.age}</p>
  <p>Attendance: ${obj.attendance}</p>
  </div>
  `;
}

school.pupils.forEach(function(obj) {
  displayPupil(obj);
});

document.getElementById('addpupil').addEventListener('submit', addPupil);
document.getElementById('delpupil').addEventListener('submit', delPupil);
document.getElementById('setprop').addEventListener('submit', setProp);

function addPupil(e) {
  e.preventDefault();
  var form = document.getElementById('addpupil');
  var name = school.nameUpperCase(form.name.value);
  var age = form.age.value;
  school.addPupil(name, age);
  var pupil = school.getPupil(name);
  displayPupil(pupil);
}

function delPupil(e) {
  e.preventDefault();
  var form = document.getElementById('delpupil');
  var name = form.name.value;
  console.log(name);
  var id = school.findPupilProperty('name', name, 'id');
  school.deletePupil(name);
  document.getElementById('pupil-' + id).innerHTML = '';
}

function setProp(e) {
  e.preventDefault();
  var form = document.getElementById('setprop');
  var name = form.name.value;
  var prop = form.prop.value;
  var value = form.value.value;
  var id = school.findPupilProperty('name', name, 'id');
  school.setPupilProperty(name, prop, value);
  document.getElementById('pupil-' + id).innerHTML = '';
  displayPupil(school.getPupil(name));
}
<div id='pupils'>

</div>

<h2>
  Functions
</h2>
<h3>
  Add Pupil
</h3>
<form id='addpupil'>
  Name: <input type='text' name='name'><br/> Age: <input type='text' name='age'>
  <input type='submit' name='submit'>
</form>

<h3>
  Delete Pupil
</h3>
<form id='delpupil'>
  Name: <input type='text' name='name'>
  <input type='submit' name='submit'>
</form>

<h3>
  Set Pupil Property
</h3>

<form id='setprop'>
  Name: <input type='text' name='name'><br/> Property: <input type='text' name='prop'><br/> Value: <input type='text' name='value'><br/>
  <input type='submit' name='submit'>
</form>

有人能找出问题所在吗?

1 个答案:

答案 0 :(得分:0)

由于return desired_pupil[find];位于findPupilProperty的末尾,

.find()找不到瞳孔时,它返回undefined,而您基本上是返回undefined['id']导致错误,

您应该为此添加检查,例如

return desired_pupil[find];

return desired_pupil ? desired_pupil[find] : null;

null只是一个建议,之后返回您需要的正确值。