在Cloud Firestore查询中使用if/else条件



我编写这些脚本是为了运行一个以HTTPGET请求的值为条件的函数。当我在页面上运行两个测试时,history变量定义正确:

  1. history == 0
  2. history == 1

问题是,无论值是0还是1,allMessage函数都将始终运行。

如果我试图反转函数(if分支上的limitMessage()else分支上的allMessage()(,则运行的是limitMessage()。我不知道为什么if else条件不能按预期工作。

//*if else condition*
var history = "<? php echo isset($_GET['history']) ? $_GET['history'] : 0; ?>";
if (history != 1) {
allMessage();
} else {
limitMessage();
}
//*limitMessage*
function limitMessage() {
firebase
.firestore()
.collection(collection)
.doc(doc)
.collection(collection)
.orderBy("time", "desc")
.limit(10)
.onSnapshot(function (querySnapshot) {
querySnapshot
.docChanges()
.reverse()
.forEach(function (change) {
var data = {
id: change.doc.id,
a: change.doc.data().a,
b: change.doc.data().b,
c: change.doc.data().c,
d: change.doc.data().d,
e: change.doc.data().e,
f: change.doc.data().f,
};
if (change.type === "added") {
msgData(data);
}
if (change.type === "modified") {
msgData(data);
}
});
});
}
//*allMessage*
function allMessage() {
firebase
.firestore()
.collection(collection)
.doc(doc)
.collection(collection)
.orderBy("time", "asc")
.onSnapshot(function (querySnapshot) {
querySnapshot.docChanges().forEach(function (change) {
var data = {
id: change.doc.id,
a: change.doc.data().a,
b: change.doc.data().b,
c: change.doc.data().c,
d: change.doc.data().d,
e: change.doc.data().e,
f: change.doc.data().f,
};
if (change.type === "added") {
msgData(data);
}
if (change.type === "modified") {
msgData(data);
}
});
});
}

使用typeof检查var的输出是一种很好的做法。

然后,您可以决定如何管理if/else语句。

您可能没有正确处理输出,以及为什么它总是在运行,无论值是0还是1。

console.log(typeof 'checkme');
// expected output: "string"
console.log(typeof 12);
// expected output: "number"
console.log(typeof undeclaredVariable);
// expected output: "undefined"
console.log(typeof true);
// expected output: "boolean"

编写好的if/else语句可能会让人感到困惑。为了更简单,我使用if作为equal to,而不是not equal,因为我发现在阅读代码和发现问题时更直观。

var history=1;
if (history == 1) {
console.log("yes");
} else {
console.log("no");
}

以下是一些可以尝试的比较运算符:

+-----------+-----------------------------------+-----------+---------+
| ==        | equal to                          | 5 == 8    | false   |
|           |                                   | 5 == 5    | true    |
|           |                                   | 5 == "5"  | true    |
| ===       | equal value and equal type        | 5 === 5   | true    |
|           |                                   | 5 === "5" | false   |
| !=        | not equal                         | 5 != 8    | true    |
| !==       | not equal value or not equal type | 5 !== 5   | false   |
|           |                                   | 5 !== "5" | true    |
|           |                                   | 5 !== 8   | true    |
+-----------+-----------------------------------+-----------+---------+

最新更新