2017-02-08 81 views
0

我使用節點紅和我有以下傳入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" ] 

我試圖解析所有這些都是「真」的項目,將它們連接起來在數組(recievingAlarms)中,解析的項目位於布爾運算符之前。我試圖用for循環來做到這一點,我很確定我創建了一個無限循環,我不知道如何糾正它。這裏是我有:

​​
+5

代替'1 + 2'使用'I + = 2'。將條件'msg.payload [i] === true'改爲'msg.payload [i] == true',因爲'「true」'是一個字符串或者與字符串「true」比較而不是布爾值true '。還有'recievingAlarms = recievingAlarms.concat(msg.payload [i-1]);' – RaR

+0

甚至'msg.payload [i] ==='true'' –

回答

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; 
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",因爲有效內容數組中的值是字符串非布爾值。

+0

有一個小錯字:忘記打開大括號'''爲''身體! –

+0

啊謝謝!將更新 – hackerrdave

1
  1. i沒有被增加,因此該循環的條件永遠不會計算爲假(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;