如何检查for循环何时完成,在循环内?

时间:2015-05-04 06:45:18

标签: javascript

这是一个快速的方法,我提出了一个更好的例子来说明我的问题。

function gi(id){return document.getElementById(id)}

    a= [1,5,1,2,3,5,3,4,3,4,3,1,3,6,7,752,23]


for(i=0; i < a.length; i++){
    /*
    if (WHAT AND WHAT){ What do I add here to know that the last value in the array was used? (For this example, it's the number: 23. Without doing IF==23.

    }
    */

    gi('test').innerHTML+=''+a[i]+' <br>';
}

(代码也可在https://jsfiddle.net/qffpcxze/1/获得)

那么,该数组中的最后一个值是23,但是我怎么知道最后一个值是循环内部的循环? (如果有意义的话,不检查简单的IF X == 23,但动态)。

4 个答案:

答案 0 :(得分:6)

编写if语句,将数组长度与i

进行比较
if(a.length - 1 === i) {
    console.log('loop ends');
}

或者您可以使用三元

(a.length - 1 === i) ? console.log('Loop ends') : '';

Demo

另请注意,我正在使用- 1,因为数组索引从0开始,并且从1开始计算返回的长度,因此要将数组与长度进行比较,我们否定-1

答案 1 :(得分:4)

if (i == a.length - 1) {
     // your code here

答案 2 :(得分:3)

你可以这样做:

function gi(id){return document.getElementById(id)}
a= [1,5,1,2,3,5,3,4,3,4,3,1,3,6,7,752,23];

for(i=0; i < a.length; i++){
  if (i==(a.length-1)){ //give your condition here
     //your stuff
  }
  gi('test').innerHTML+=''+a[i]+' <br>';
}

答案 3 :(得分:2)

你可以试试这个:

if(i === a.length - 1) {
    //some code
}