简体   繁体   English

分号在for循环中如何工作?

[英]How do the semicolons work in the for loop?

I am writing a function that raises a value to another value without using the exponent operator. 我正在编写一个不使用指数运算符就将一个值提高到另一个值的函数。 I understand the syntax of these kinds of loops as being that initialised values go before the first semicolon, a condition goes between the first and the second semicolon, and after the second semicolon is the looping operations. 我理解这类循环的语法,因为初始化值位于第一个分号之前,条件位于第一个和第二个分号之间,而第二个分号之后是循环操作。

I am confused because I think this code should be broken, but it appears to return the correct value. 我很困惑,因为我认为该代码应该被破坏,但它似乎返回正确的值。 When I put result *= base after count++ inside the parenthesis, then the code does not return the correct value. 当我将result *= base放在括号内的count++之后时,则代码未返回正确的值。 Why is this? 为什么是这样?

 //Power function function power(base, exponent) { var result = 1 var count = 0 for (; count < exponent; count++) result *= base return result; } print(power(5, 2)); 

The blank ; 空白; just acts as a placeholder in this case. 在这种情况下只是充当占位符。 Because you declared count = 0 above this for loop, this ; 因为您在此for循环上方声明count = 0 ,所以; is just there so that declaration isn't overwritten: 只是在那里,所以声明不会被覆盖:

 var count = 0; for(/*var count=0*/; count < 4; count++){ document.write(count); } 

PS I commented out var count = 0 because that is essentially what the code is representing (because you called that earlier). PS我注释掉var count = 0因为从本质上讲,这就是代码所代表的含义(因为您之前已经调用过)。

It is possible to do what you want in javascript. 可以在javascript中执行您想要的操作。 I think the only problem is that you didn't use brackets. 我认为唯一的问题是您没有使用方括号。 This will work. 这将起作用。

 //Power function function power(base, exponent){ var result = 1; var count = 0; for (; count < exponent; count++, result *= base) {} return result; } document.write(power(5, 2)); //returns 25 

But this won't because even if you don't indent return, it will be executed in the for loop and return during the first iteration. 但这不是因为即使您不缩进return,它也会在for循环中执行并在第一次迭代中返回。 I ran in this issue when I tried your code snipplet so I think it is your issue : 我在尝试您的代码片段时遇到了这个问题,所以我认为这是您的问题:

 //Power function function power(base, exponent){ var result = 1; var count = 0; for (; count < exponent; count++, result *= base) //notice the missing brackets return result; } document.write(power(5, 2)); //returns 25 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM