You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 22:30:55