所以我正在尝试制作一个接受名称的表单。 输入字段将输入一个名称。当您按下提交按钮时,仅当
时,它才会将名称添加到数组中name!=null
和之后数组将显示在输入框下方。
为了在添加到数组之前检查输入,我使用了以下代码:
var name = String(this.studentName);
name = name.trim();
this.currentStudentName = name;
if (this.listOfNames.includes(this.currentStudentName)) {
alert('Duplicate name found!');
} else if (this.currentStudentName === '') {
alert('Emptry entry!');
} else {
this.listOfNames.push(this.currentStudentName);
}
}
代码在处理重复值和空值时工作正常,但是
如果在加载页面时直接按提交按钮,则未定义将添加到数组中,并且数组显示的第一个条目为“未定义”,但是 我不想将未定义的内容保存到数组中。
为了避免在页面加载时将 undefined 添加到数组中,您需要单独处理这种情况。在将输入添加到数组之前,您可以添加一个条件来检查输入是否未定义。这是修改后的代码:
handleSubmit() {
var name = String(this.studentName);
name = name.trim();
this.currentStudentName = name;
if (this.currentStudentName === undefined) {
alert('Name is undefined!');
} else if (this.listOfNames.includes(this.currentStudentName)) {
alert('Duplicate name found!');
} else if (this.currentStudentName === '') {
alert('Empty entry!');
} else {
this.listOfNames.push(this.currentStudentName);
}
}