开发姓名提交表单时,页面加载后点击提交数组添加undefined的问题
解决表单提交时存入无效值的问题
页面加载完成后直接点击提交,this.studentName的初始值为undefined,执行String(this.studentName)会将其转为字符串"undefined"——这个值既非空串也未重复,因此会被存入数组。你需要在验证流程最前端添加判断,拦截undefined或null这类无效输入。
修改后的代码如下:
var name = this.studentName; // 先判断原始值是否未定义或为空 if (name === undefined || name === null) { alert('请输入姓名!'); return; } // 转为字符串并去除首尾空格 name = String(name).trim(); this.currentStudentName = name; if (this.listOfNames.includes(this.currentStudentName)) { alert('姓名重复!'); } else if (this.currentStudentName === '') { alert('输入不能为空!'); } else { this.listOfNames.push(this.currentStudentName); }
关键改动:
- 把
undefined/null的检查放在最前面,直接拦截这类无效输入,避免后续不必要的字符串转换操作 - 调整验证顺序,优先处理最基础的“未输入”情况,逻辑更清晰
修改后,空点提交会弹出提示,不会往数组中存入undefined或"undefined"这类无效值。
内容的提问来源于stack exchange,提问作者potatomasher
相关产品推荐
相关产品推荐

