javascript - 在 Javascript 中检查结果时如何修复“未定义”对象?
问题描述
所以我遇到了在代码顶部定义的变量(结果)的问题,但是一旦我稍后控制台记录它,它就会返回为未定义。我正在设置一个时事通讯表单,这是检查用户是否已经注册的逻辑,并弹出一条关于他们是否注册的消息。
我试图将变量设置为布尔值,但代码正在检查特定的用户输入,所以这不起作用,我也尝试在代码的不同部分设置变量,但没有运气。不幸的是,当谈到 javascript 时,我还是个新手。
var result = coll.doc(email);
exists.then(val => {
console.log(val)
// perform an action according to existing document or not
if (val == true) { // document already exists
alert("already registered to our newsletter. Thank you for your interest!");
console.log(message)
} else if (val == false) { // document doesn't exist
console.log('setting the doc');
// set the new document
coll.doc(email).set({
firstname: firstName,
lastname: lastName,
nation: country,
type: typeofInv
})
.then(result => { // if no error
console.log('Received ticket: ' + result);
if (result) { // check for certain characteristics in the result here
alert("You are successfully registered. We will be in touch!");
}
console.log(message)
})
预期的结果是结果变量应该控制台记录用户输入的电子邮件,以便我可以检查它的某些特征,但是当我控制台记录它时我得到一个未定义的结果。对此有什么想法吗?
解决方案
coll.doc(email) 可能会失败并且结果保持为空值,您应该在调用 coll.doc(email) 之前尝试为 var result 赋值;像这样:
var whatevervar = "";
或者如果是一个整数:
var whatevervar = 0;
of if 是一个布尔值:
var whatevervar = false;
ETC...
像这样:
var result = "";
result = coll.doc(email);
exists.then(val => {
console.log(val)
// perform an action according to existing document or not
if (val == true) { // document already exists
alert("already registered to our newsletter. Thank you for your interest!");
console.log(message)
} else if (val == false) { // document doesn't exist
console.log('setting the doc');
// set the new document
coll.doc(email).set({
firstname: firstName,
lastname: lastName,
nation: country,
type: typeofInv
})
.then(result => { // if no error
console.log('Received ticket: ' + result);
if (result) { // check for certain characteristics in the result here
alert("You are successfully registered. We will be in touch!");
}
console.log(message)
})
推荐阅读
- knockout.js - 可观察到的变化剔除的触发功能
- javascript - 从打字稿编译后,此关键字在浏览器中给出空引用错误
- redux-form - 如何初始化表单错误?
- angular - Angular Material - 有条件地禁用动画
- c - CryptGenRandom 返回不统一的结果
- javascript - vue:属性或方法“priceFilter”未定义
- c# - 我如何知道哪个参数导致 OracleCommand Insert 上的 FormatException(“输入字符串格式不正确”)?
- python - Python - 意外替换原始数据
- javascript - 在 VueJS 中将我的组件从 Javascript 重构为 Typescript 时迷失了方向
- ios - iOS:重命名我的应用程序,但共享我的应用程序仍使用旧名称