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

标签 javascript

这是一个非常基本的 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/

相关文章:

javascript - 使用数组中的 Rest 运算符进行解构 : Grabbing Array elements as variables as well as capturing remaining array in JavaScript

3 个独立 div 的 javascript onmouseover 可见性切换

javascript - scrollTop 不适用于 jQuery 弹出框

javascript - 如何使用 D3 将 JSON 数据更改为 Javascript 对象数组

javascript - 为什么 parseInt 与 Array.map 一起使用时返回 NaN?

javascript - 除了 document.location.hash 之外,还有其他方法可以将参数传递给 javascript 吗?

javascript - 在 Next JS 中不触发页面更改事件的情况下更新路由器查询

javascript - 为中国用户动态切换 Google Maps API URL

javascript - 理解和阅读 jQuery

javascript - 指针事件 : none for inside of div and pointer-events: all for outside (reverse mode of normal div) - walkthrough tour container