我使用node-red并且我有以下传入的msg.payload:
[ "=00ECY20WA200_RECV_P1SEL", "true", "=00ECY20WA200_RECV_P2SEL", "true", "=00ECY20WA300_RECV_P2SEL", "true", "=00ECY20WA300_RECV_P1SEL", "true", "=00ECY20WA202_RECV_P1SEL", "true", "=00ECY20WA202_RECV_P2SEL", "false", "=00ECY20WA303_RECV_P2SEL", "true", "=00ECY20WA303_RECV_P1SEL", "true", "=00ECY20WA204_RECV_P1SEL", "false", "=00ECY20WA204_RECV_P2SEL", "true", "=00ECY20WA305_RECV_P2SEL", "false", "=00ECY20WA305_RECV_P1SEL", "false", "=00ECY20WA205_RECV_P1SEL", "false", "=00ECY20WA205_RECV_P2SEL", "false", "=00ECY20WA306_RECV_P1SEL", "true", "=00ECY20WA306_RECV_P2SEL", "true", "=00ECY20WA206_RECV_P1SEL", "false", "=00ECY20WA206_RECV_P2SEL", "true", "=00ECY20WA307_RECV_P1SEL", "true", "=00ECY20WA307_RECV_P2SEL", "true", "=00ECY20WA207_RECV_P1SEL", "false", "=00ECY20WA207_RECV_P2SEL", "false", "=00ECY20WA308_RECV_P1SEL", "false", "=00ECY20WA308_RECV_P2SEL", "true", "=00ECY20WA208_RECV_P1SEL", "false" ]
我试图解析所有" true"并将它们连接在一个数组(recievingAlarms)中,解析后的项目就是位于布尔运算符之前的项目。我尝试用for循环来做这件事,我很确定我已经创建了一个无限循环,我不确定如何纠正它。这就是我所拥有的:
var recievingAlarms = [];
for (i = 1; i < msg.payload.length; i+2)
if(msg.payload[i] === true) {
recievingAlarms.concat(msg.payload[i-1]);
}
msg.payload = recievingAlarms;
return msg;
答案 0 :(得分:3)
你的循环现在是无限的,因为你没有增加i
,增加i
,你需要用i+2
替换i += 2
,以便重新分配它的值:
var receivingAlarms = [];
for (var i = 1; i < msg.payload.length; i += 2) {
if(msg.payload[i] === "true") { //replace true with "true"
receivingAlarms.push(msg.payload[i-1]); //replace concat with push because msg.payload[i - 1] is not an Array
}
}
msg.payload = receivingAlarms;
return msg;
您还需要将.concat()
更改为.push()
- .concat()
用于合并/合并两个数组,但msg.payload[i-1]
的结果不是数组。此外,需要修改true
的条件检查以检查字符串"true"
,因为有效内容数组中的值是字符串而不是布尔值。
答案 1 :(得分:1)
这是您的解决方案
var recievingAlarms = [];
for (i = 1; i < msg.payload.length; i=i+2)
if(msg.payload[i] == "true") {
recievingAlarms=recievingAlarms.concat(msg.payload[i-1]);
}
msg.payload = recievingAlarms;
return msg;
答案 2 :(得分:1)
i
永远不会增加,因此循环的条件永远不会评估为false(i
将始终小于.length
)。"true"
和true
不属于同一类型(一个是字符串,另一个是布尔值)。请将msg.payLoad[i]
与"true"
进行比较。concat
汇总了两个数组。使用push
向数组添加新项目。var recievingAlarms = [];
for (i = 1; i < msg.payload.length; i += 2)
if(msg.payload[i] === "true")
recievingAlarms.push(msg.payload[i - 1]);
msg.payload = recievingAlarms;