如何在javascript中转换while循环到for循环

How can I convert while loop to for loop in javascript?

本文关键字:循环 while for 转换 javascript      更新时间:2023-09-26

我有问题,转换while循环到for循环。这将如何在一个循环格式,任何帮助将是非常感激。实际文件存储在github上> github link

          //language
          while ((m = regex.exec(str)) !== null) {
              if (m.index === regex.lastIndex) {
                  regex.lastIndex++;
              }
              m.forEach((match, groupIndex) => {
                  output = output+`{'n"Language": "${match}"'n`;
              });
          }

回想一下while循环的标准形式:

while (test) {
    body;
}

for环的标准形式:

for (initialization; test; update) {
    body;
}

这是可能改变你的whilefor,但它没有多大意义:

for (m = regex.exec(str); m !== null ; m = regex.exec(str)) {
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    m.forEach((match, groupIndex) => {
        output = output + `{'n"Language": "${match}"'n`;
    });
}

注意初始化和更新是相同的;重复代码。

交替

:

for ( ; (m = regex.exec(str)) !== null ; ) {
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    m.forEach((match, groupIndex) => {
        output = output + `{'n"Language": "${match}"'n`;
    });
}

注意初始化和更新都是空的