Javascript 为什么这个回调中的条件总是返回false?
我有一个基于Vue的家庭水疗中心。其中一个组件由Javascript 为什么这个回调中的条件总是返回false?,javascript,if-statement,conditional-statements,conditional-operator,Javascript,If Statement,Conditional Statements,Conditional Operator,我有一个基于Vue的家庭水疗中心。其中一个组件由v-if=“isDisplayed”驱动 通过收听MQTT主题(参见脚注)设置此显示,并通过以下函数处理接收到的新消息(我专门使用'hello'而不是false,以确保开关转到那里)。感兴趣的主题是display\u school\u edt mqttMessage(topic, message) { console.log(`App.vue received topic ${topic} with payload '${message
v-if=“isDisplayed
”驱动
通过收听MQTT主题(参见脚注)设置此显示,并通过以下函数处理接收到的新消息(我专门使用'hello'
而不是false
,以确保开关转到那里)。感兴趣的主题是display\u school\u edt
mqttMessage(topic, message) {
console.log(`App.vue received topic ${topic} with payload '${message}'`)
if (topic === "dash/reload") {
window.location.href = window.location.href
document.location.reload(true);
}
if (topic === "dash/darkmode") {
this.nightmode = JSON.parse(message) ? "night" : "day";
}
// this is the part I have problems with, I left everything for completness
if (topic === "display_school_edt") {
console.log(`edt display received: '${message}'`);
if (message === 'on') {
this.isEdtDisplayed = true
} else {
this.isEdtDisplayed = 'hello'
}
// I initially went for the ternary below - same results
// message === "on" ? this.isEdtDisplayed = true : this.isEdtDisplayed = 'hello';
console.log(`new edt display: ${this.isEdtDisplayed}`);
}
}
当我发布到受监控的主题display\u school\u edt
(两次:一次是打开
,另一次是关闭
),以下是我在控制台上得到的信息:
换句话说,无论接收到打开
或关闭
,条件始终为假
我的代码显然有点问题,但我看得越多,它看起来就越好
脚注:事实上,特定的协议并不重要(这是一种经常与IoT一起使用的总线),您可以假设执行mqttMessage()
时,参数topic
和message
都是字符串。如果message
是字符串类型,这确实是意外的。然而,它可能不是,并且只有当您输出消息时,您才将其强制为字符串。因此,如果您从以前的输出中看到它强制为“否”,那么在if
条件中,您应该执行相同的操作,并强制转换为字符串:
if (message+'' === 'no')
注意:这将调用message.toString()
,就像在模板文本中将其引用为${message}
关于脚注:您能调试并确保message
是字符串吗?比如console.log(消息类型)
。我认为这就是问题所在,你应该做if(message+''=='on')
--将消息
转换成字符串。@trincot:ahhh,你说得对。实际上这是一件奇怪的事情(因此与MQTT协议BTW不一致):object
。当我console.log(message)
看到Uint8Array(3)[111、102、102]
。我正在读有关。编辑toString()就是解决方案。你介不介意引导一个答案,这样我就可以用引用编辑它并接受它?谢谢我建议编写String(message)
或message.toString()
而不是通过连接强制执行。@Bergi:我实际上使用了.toString()
,以便在一个月后回到这段代码并开始思考我的意思时更清楚一些。