gpt4 book ai didi

javascript - 基本 1-10 计数器中的变量分配

转载 作者:行者123 更新时间:2023-11-28 01:37:07 25 4
gpt4 key购买 nike

这是一个非常基本的 10 计数器:

for (var i = 1; i <= 10; i++) {
console.log (i); // outputs 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
}

console.log(i);

我期望全局空间中 i 的值为 10。它是 11。我能想到的唯一原因是它被分配 11 来打破循环 i <= 10。

这个理由正确吗?

最佳答案

是的,for 循环以这种方式工作:

for (/*initial conditions set at beginning of loop*/; 
/*break condition checked before entering the loop each time*/;
/*command to execute at the end of each loop*/)
{
// stuff to do during loop
}

所以你的假设是正确的,for 循环运行直到 i = 11 因为这是循环第一次达到中断条件。

创建 For 循环是为了避免重复的 while 或 do/while 循环。上面的循环可以被认为是:

/*initial conditions set at beginning of loop*/
while (/*break condition checked before entering the loop each time*/){
// stuff to do during loop
/*command to execute at the end of each loop*/
}

关于javascript - 基本 1-10 计数器中的变量分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21412426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com