Node-RED教程 – For循环的使用

Node-RED教程 – For循环的使用

循环重复执行一个动作。

有几个循环语法,它们是 for、while、do while。

到目前为止,最常见的是for 循环。一般格式为:

for(开始;条件;步骤){
// ...循环体...
}

使用示例:

let count=5
for(let x=0;x<count;x++)
{
node.log("count=" + x);
}

结果输出从 0 到 4 的计数值。

很多时候,我们需要在 for 循环中发送消息来做到这一点,我们使用 node.send(msg) 方法

let count=5
for(let x=0;x<count;x++)
{
msg.payload=x;
node.send(msg);
}

遍历数组

let names= [Tom,Jack.Jane,han-link];

for (let i=0;i<names.length;i++)
{
node.log("name = "+names[i];
}

使用for…of

const fruits = ['apples', 'pears', 'oranges'];

for (const fruit of fruits) {
    node.log(fruit);
}

// 输出: "apples"
// 输出: "pears"
// 输出: "oranges"

遍历对象

有两种常用方法。

首先在使用 for 属性,如下所示:

const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
    node.log(property + ":"+ object[property]);
}

// 输出:
// "a: 1"
// "b: 2"
// "c: 3"

我们还可以获取Objectkey并使用key遍历对象。

第一步是使用 Object.keys() 函数获取key。这将返回一个key数组。

continue 和 break

continue 语句用于将循环推进 1 个元素,break 用于退出循环。

使用 continue。

const fruits = ['apples', 'pears', 'oranges'];

for (const fruit of fruits) {
    if (fruit=="pears")
        continue;
    else
     node.log(fruit);
}

// 输出: "apples"
// 输出: "oranges"

使用break

const fruits = ['apples', 'pears', 'oranges'];

for (const fruit of fruits) {
    if (fruit=="pears")
        break;
    else
     node.log(fruit);
}

// 输出: "apples"

多个变量

初始化和递增多个变量,如下所示。但是,只有一个条件。

for (let x = 0, y = 0; x < 2; x++, y++)
 {
  node.log("variable x: " + x);
  node.log("variable y: " + y);
 
}

// 输出: 0,1

使用Step 或 Increment

回到我们的一般for循环:

for (begin; condition; step) {
// ... loop body ...
}

最常见的步骤是递增 1,因此我们有了语法 x++。

但是,我们可以增加任何数字,也可以减少。

所以 x– 将减少计数,而 x=x+5 会将计数增加 5。

示例1

for (let x = 0; x < 21; x=x+5)
 {
  node.log("variable x: " + x);
 
}

示例2

for (let x = 0; x < 20; x=x+5)
 {
  node.log("variable x: " + x);
 
}

示例3

const fruits = ['apples', 'pears', 'oranges']; 
for (const fruit of fruits) 
{ 
    if (fruit == "oranges")
     continue; 
     else 
     node.log(fruit); 
     }
return msg;
© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称快捷回复

    暂无评论内容