Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么这个回调中的条件总是返回false?_Javascript_If Statement_Conditional Statements_Conditional Operator - Fatal编程技术网

Javascript 为什么这个回调中的条件总是返回false?

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

我有一个基于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}'`)
      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()
,以便在一个月后回到这段代码并开始思考我的意思时更清楚一些。