在 JS 中,我偶然发现了一种 for 循环,它是 for(;;)
,其功能类似于 while(true)
循环。这个for循环括号里的分号有什么作用?
最佳答案
for (statement 1; statement 2; statement 3) {
code block to be executed
}
语句 1 是可选的,在循环(代码块)开始之前执行。
var i = 0;
var length = 10
for (; i < length; i++) {
//The for loop run until i is less than length and you incerement i by 1 each time. javascript doesnt care what you do inside, it just check whether you have variable with name i and length
}
语句 2 再次是可选的,它定义了运行循环(代码块)的条件。
var i = 0;
var len = 100;
for (i = 5; ; i++) {
//Here you are just initializing i with 5 and increment it by 1 there is no break condition so this will lead to an infinite loop hence we should always have a break here somehwere.
}
语句 3 是可选的,每次在循环(代码块)执行后执行。
var i = 0;
var length = 100;
for (; i < length; ) {
//Here you are just checking for i < length which is true. If you don't increment i or have an break it will turn into infinite loop
}
简而言之,当您没有条件或初始化时,它会变成无限循环。
关于javascript - for(;;)循环解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44481466/