当某些元素为空时,通过数组循环?

时间:2013-03-09 00:02:46

标签: jquery

我有一个多维答案数组,可以有2个,3个或4个答案。

answers[0]{'Answer A', 'Answer B', 'Answer C', 'Answer D'}
answers[1]{'Answer A', 'Answer B'}
answers[2]{'Answer A', 'Answer B', 'Answer C'}

我想遍历每一个,如果答案存在显示答案,如果答案不存在,那么我想显示一个空白框。

for (var i = 0, len = 4; i < len; i++) {

    alert(answers[n][i]);               

}

如果答案存在于数组中然后对其采取行动,我如何检查上述循环?

2 个答案:

答案 0 :(得分:0)

if (answers[n][i]) {
//do something
}

答案 1 :(得分:0)

工作示例: http://jsfiddle.net/NXtyh/1/

如果我理解正确,你想要在内部数组中循环4次,无论它的实际大小如何。

var n,i;
var maxLength = 4;

for (n = 0; n < answers.length; n++){
    if (!answers[n]) answers[n] = [];
    for (i = 0; i < maxLength ; i++) {

       if (!answers[n][i]) {
          alert("Answer [" + n + "," + i + "] is empty");
       } else {
          //console.log ("Answer [" + n + "," + i + "] is " + answers[n][i]);
       }
    }
}