简体   繁体   English

JavaScript变量在for循环中变化

[英]JavaScript variable changes inside for loop

i have this for loop: 我有这个for循环:

for (var i = 0; i < pictures.length; i++) {
    var mod = i % 4;
    alert(mod); // first
    //get the current row
    if (mod == 0)
    {
        alert(mod); //second
        tableBody.innerHTML += "<tr>";
    }
    tableBody.innerHTML += "<td><img style='width:146px; height:146px;' src='" + pictures[i].source + "'></td>";
    if (mod == 0)
        tableBody.innerHTML += "</tr>";
}

how come my first alert shows the result of the math calculation inside "mod" variable, and the second alert show always zero ?? 为什么我的第一个警报显示“mod”变量内的数学计算结果,第二个警报显示为零?

因为当且仅当mod == 0时才执行第二个警报。

第二个警报将显示0,因为你有一个if()语句,它检查mod == 0

C'mon your second alert is inside if() statement. 来吧,你的第二个警报是在if()语句中。 It will get executed only when mod=0. 只有当mod = 0时才会执行它。 If mod=0, it will enter if loop and execute the statements there. 如果mod = 0,它将进入if循环并执行那里的语句。 Your if statement contains alert(mod). 你的if语句包含alert(mod)。 So, it will print the value of mod which is equal to zero. 因此,它将打印mod的值,该值等于零。 And in your first alert, it will calculate the value of mod and will print whatever is the value of variable mod(irrsepective of the fact whether it is zero). 在你的第一个警报中,它将计算mod的值,并将打印变量mod的值(无论是否为零)。

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

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