简体   繁体   English

javascript中的循环语句行为异常

[英]loop statement in javascript not behaving as expected

The below code will only execute the alert statement statement once then break. 下面的代码将只执行一次alert语句,然后中断。 For example i = 2000 i was expecting it to be printed 4 times will it reaches the condition. 例如,我= 2000,我期望它将达到条件时被打印4次。

var i = str.value;

for (i; i <= 2400; i += 100) {
    alert(i);
}

If the type of str.value is a string, then it execute for the first time, the next time it will fail, because 如果str.value的类型是字符串,则它将首次执行,下次将执行失败,因为

i += 100

will concatenate 100 as a string to 2000 , instead of adding. 100作为字符串连接到2000 ,而不是添加。 You can check that like this 你可以这样检查

console.log('2000' + 100);
# 2000100

which will be greater than 2400 大于2400

console.log('2000100' > 2400);
# true

So, you should be converting i to an integer, like this 因此,您应该将i转换为整数,像这样

var i = parseInt(str.value, 10);

with that change, the output becomes 更改后,输出变为

2000
2100
2200
2300
2400

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

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