我有这个简单的for循环但不幸的是我无法成功运行它。
这就是我所拥有的:
For Loop
var imagesPerPage = 2
for (i = 0; i < response.d.length; i++) {
if (i > imagesPerPage) {
alert('more');
}else{
alert('less');
}
}
当我运行此代码时first
如果我有&lt; = 2 ,那么我会"less"
提醒twice
。
但当我有&gt; 2 然后我得到"less"
提醒twice
和"more"
提醒once
。
谁能说我哪里出错?
答案 0 :(得分:6)
为什么不为此使用简单的if
构造?
var imagesPerPage = 2
if ( response.d.length > imagesPerPage ) {
alert('more');
} else {
alert('less');
}
在您的代码中,循环始终运行response.d.length
次。在前两次你的虚假部分如果发生火灾并导致两个“更多”警报。之后所有其他运行使用if子句的真实部分并返回“更多”。无论如何,无论你发出警报,所有的运行都会完成。
但是,您可以通过在要离开循环的位置插入break
命令来停止循环。然而,这通常导致非常不清楚的代码,因此应尽可能避免。 (此外,我怀疑,这将是你想要的行为。)
答案 1 :(得分:3)
为什么需要for循环?我认为这应该足够了:
if ( response.d.length > imagesPerPage )
{
alert('more');
}
else
{
alert('less');
}