分号在& for的开头如何工作? [英] How does the semicolon work at the beginning of "for"?

查看:74
本文介绍了分号在& for的开头如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在Mozilla网站上遇到了这段代码,虽然对我来说,它看起来很破损,但是我可能不熟悉它的用法:

I just came across this code on the Mozilla site and, while to me it looks broken, it's likely I am not familiar with its use:

for (; k < len; k++)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }

分号在循环开始时如何工作?

How does the semicolon work at the beginning of the loop?

完整代码位于此处.

推荐答案

第一部分是用于初始化变量的 initial-expression (请参见

The first part is the initial-expression that is used to initialize variables (see for construct):

 for ([initial-expression]; [condition]; [final-expression])
    statement

在这种情况下,方括号表示它是可选的.因此,如果您没有要初始化的变量,则无需编写任何初始化程序表达式.就像在这种情况下, k for 循环之前被初始化:

The brackets mean in this case that it’s optional. So you don’t need to write any initializer expression if you don’t have any variables to initialize. Like in this case where k is initialized before the for loop:

var k = n >= 0
      ? n
      : Math.max(len - Math.abs(n), 0);

for (; k < len; k++)
{
  if (k in t && t[k] === searchElement)
    return k;
}

您也可以将其写为 initial-expression 部分,但可读性不强:

You could also write it as initial-expression part but that wouldn’t be that readable:

for (var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); k < len; k++)
{
  if (k in t && t[k] === searchElement)
    return k;
}

这篇关于分号在&amp; for的开头如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆