How does the semicolon work at the beginning of “for”?

后端 未结 2 782
执念已碎
执念已碎 2021-01-05 14:15

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++)
    {         


        
相关标签:
2条回答
  • 2021-01-05 14:55

    it's mean that declaration and initialization k variable is something upper;

    If you want skip some for section, you just put semicolon, e.g.:

    for (;;) {
      //infinite loop
    }
    
    0 讨论(0)
  • 2021-01-05 15:11

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

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

    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;
    }
    

    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;
    }
    
    0 讨论(0)
提交回复
热议问题