循环重复执行一个动作。
有几个循环语法,它们是 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"
我们还可以获取Object的key并使用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;
© 版权声明
您必须遵守我们的协议,如果您下载了该资源行为将被视为对《免责声明》全部内容的认可,本网站资源大都来自原创,也有少部分来自互联网收集,仅供用于学习和交流,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。敬请谅解! 侵权删帖/违法举报/投稿等事物联系邮箱:hanlink@189.cn
THE END
暂无评论内容