If语句为True时无输出、始终执行Else分支的问题咨询
问题原因分析
你的代码逻辑问题出在**forEach循环的执行逻辑**上:
- 遍历
querySnapshot里的每一个文档时,每一次循环都会直接覆盖promptContent.innerText的值。 - 哪怕某个文档匹配了
userEmail.value(触发If分支显示"Email already exists"),只要后续还有不匹配的文档,就会被Else分支的"Account created."覆盖,最终页面显示的是最后一次循环的结果。 - 注释掉Else语句后,只有匹配的文档会修改文本,不匹配的不会改动,所以能得到正确结果。
修复方案
可以先设置默认状态,再遍历查找匹配项,找到后再更新文本:
else if (dropDown.value === "New") { db.collection("testing").onSnapshot((querySnapshot) => { // 默认设为"Account created.",假设不存在匹配邮箱 promptContent.innerText = "Account created."; querySnapshot.forEach((doc) => { if (doc.data().userEmail === userEmail.value) { // 找到匹配项,更新文本 promptContent.innerText = "Email already exists"; // 找到后跳出循环,避免无效遍历 return; } }) }) }
更高效的写法是用some()方法直接判断是否存在匹配文档,不用遍历全部:
else if (dropDown.value === "New") { db.collection("testing").onSnapshot((querySnapshot) => { const emailExists = querySnapshot.docs.some(doc => doc.data().userEmail === userEmail.value); promptContent.innerText = emailExists ? "Email already exists" : "Account created."; }) }
内容的提问来源于stack exchange,提问作者alittlecurryhot
相关产品推荐
相关产品推荐

