Search code examples
javascriptnode.jsibm-cloudnode-red

NodeRed, Not able to access the variables within the nested for loops


I am relatively new to nodejs and my code inside the function node looks like this,

var temper=parseInt(msg.payload.temperature);
temp=temper;
var seconDigit=temp%10;
temp=parseInt(temp/10);
var first=temp%10;
temp=temp/10;
var count;

//msg={"payload":{"one":first,"two":seconDigit}};
//return msg;
if(msg.payload.screen=="on"){


var firstCol="*,*,#800000";
count=0;

for(var i=1;i<=2;i++){

    for(var j=1;j<=6;j++){

        if(count<first){

            firstCol=firstCol+","+i.toString()+","+j.toString()+",#C0C0C0";
            count++;
        }

    }
}

count=0;
for(var i=5;i<=6;i++){
    for(var j=1;j<=6;j++){
        if(count<seconDigit){
            firstCol+=","+i.toString()+","+j.toString()+",#C0C0C0";
            count++;
        }

    }
}
//msg={"payload":first};
//return msg;
msg={"payload":firstCol};
return msg;
}
else if(msg.payload.screen=="off"){

var firstCol="*,*,#008000";
count=0;
for(var i=1;i<=2;i++){
    for(var j=1;j<=6;j++){
        if(count<firstDigit){
            firstCol+=","+i.toString()+","+j.toString()+",#C0C0C0";
            count++;
        }

    }
}
count=0;
for(var i=5;i<=6;i++){
    for(var j=1;j<=6;j++){
        if(count<seconDigit){
            firstCol=firstCol+","+i.toString()+","+j.toString()+",#C0C0C0";
            count++;
        }

    }
}
msg={"payload":firstCol};
return msg;
}
else{
    msg={"payload":"*,*,#000000"};
    return msg;
}

I am unable to access the first and seconDigit variables inside the nested for loop, that part of the code is not being executed. My expected result should be one two strings. one is *,*,#000000 and the other long string based on the temp value looks something like *,*,...... But when I uncomment the couple of lines on top, they seem to work fine. What am I doing wrong and what should I change to access the values inside the for loop?


Solution

  • Even I had the same problem few days ago. Instead of connecting the node from which you are getting msg.payload.temperature. Just use global.set("first",msg.payload.temperature);
    in that node and access it using
    temp=global.get("first");.

    So the top part of your code will be

    temp=global.get("first");
    var first=parseInt(temp/10);
    var seconDigit=parseInt(temp%10);