I just made the jump from IDE to Node-RED where JavaScript comes into play. I am eager to learn but my knowledge is limited knowledge.
What I am trying to do, is simple to check the msg.payload
, if the value is larger than 25 then I want to return 1 else I want to return 0.
I have tried different codes, but it does not work.
m = msg.payload;
if (m < 25)
{
return 1;
}
else if (m > 25)
{
return 0;
}
and
m = msg.payload;
if (m < 25)
{
return 1;
}
else ()
{
return 0;
}
For Node-RED function nodes you must return a msg
object not just a value.
So the correct form for this test is as follows.
if (msg.payload > 25) {
msg.payload = 1
} else {
msg.payload = 0;
}
return msg;
You should learn comparision operator
where >
denotes greater than
and <
denotes lesser than
, you can simplify using ternary operator as
return msg.payload > 25 ? 1 : 0;
DEMO WITH IF ELSE
function check(m){ if (m > 25){ return 1; } else { return 0; } }; console.log(check(50));
DEMO WITH TERNARY
function check(m){ return m > 25 ? 1 : 0; }; console.log(check(50));
You can do it in one line:
return msg.payload > 25 ? 1 : 0;
or if you just need booleans (true/false):
return msg.payload > 25;
Try this:
if (Number(m) > 25){
return 1;
}
else{
return 0;
}
You are making a very silly mistake of less than and greater than sign. Hope it helps you.
m = msg.payload;
if (m > 25)
{
msg.payload=1;
}
else if (m < 25)
{
msg.payload=0;
}
return msg;
You can simplify this a good bit, the else
isn't even needed in this case:
if (m > 25) {
return 1;
}
return 0;
When the return
inside the if
statement is executed, the code that follows won't be run... making the else
statement unnecessary.
The else is redundant when you're just returning like that, and you've got your comparison operators backwards. Right now it'll return 1 if it's less than 25, not greater than.
if (msg.payload > 25) {
return 1;
}
return 0;
As you have mentioned that you want to return 1 if value is greater than 25. Please check that you have written wrong condition. Your condition must be this:
if ( m > 25 ){
return 1;
} else {
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.