遍历数组并解析

Looping through an Array and parsing

我正在使用 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;

这是您的解决方案

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;

您的循环现在是无限的,因为您没有递增 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() 用于 merging/combining 两个数组,但 msg.payload[i-1] 的结果不是大批。此外,需要修改 true 的条件检查以检查字符串 "true",因为有效负载数组中的值是字符串而不是布尔值。

  1. i 永远不会递增,因此循环条件永远不会计算为 false(i 将始终小于 .length)。
  2. "true"true 不是同一类型(一个是字符串,另一个是布尔值)。将 msg.payLoad[i]"true" 进行比较。
  3. 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;