JavaScript While Loop Array Undefined输出

时间:2018-03-30 10:20:55

标签: javascript arrays loops sorting

var v = 0
var x = ["a", "b", "c"];
var beasts = [{
  "kind": [{
    "q": "a"
  }, {
    "q": "b"
  }, {
    "q": "c"
  }]
}];
while (x.indexOf(beasts[0].kind[v].q)) {
  v++
  console.log("loop")
}

未定义输出,怎么回事?

4 个答案:

答案 0 :(得分:1)

v == 0时,测试为x.indexOf("a")。这将返回0,这是假的,因此循环立即结束。

使用indexOf()的正确方法是x.indexOf(...) != -1

您还需要检查v是否在beasts[0].kind范围内,否则当您到达阵列末尾时会出现错误。



var v = 0
var x = ["a", "b", "c"];
var beasts = [{
  "kind": [{
    "q": "a"
  }, {
    "q": "b"
  }, {
    "q": "c"
  }]
}];

while (v < beasts[0].kind.length && x.indexOf(beasts[0].kind[v].q) != -1) {
  v++
  console.log("loop")
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以在代码段中看到while中的条件评估为0这是一个假值。 While循环永远不会运行!

&#13;
&#13;
var v = 0
var x = ["a","b","c"];
var beasts = [{"kind": [{"q": "a"}, {"q": "b"}, {"q": "c"}]}];
while (x.indexOf(beasts[0].kind[v].q)) {
v++
console.log("loop")
}
console.log(beasts[0].kind[v].q);
console.log(x.indexOf(beasts[0].kind[v].q));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您错过了检查undefined beasts[0].kind[v]的{​​{1}}案例,因为您在vwhile的值增加v的最后一个值将超过内部数组的长度,这将导致undefined。您也不需要indexOf计算。

var v = 0
var x = ["a","b","c"];
var beasts = [{"kind": [{"q": "a"}, {"q": "b"}, {"q": "c"}]}];
while (beasts[0].kind[v]) {
  v++;
  console.log("loop");
}

但是如果你想确保属性q,你可以使用这个

var v = 0
var x = ["a","b","c"];
var beasts = [{"kind": [{"q": "a"}, {"q": "b"}, {"q": "c"}]}];
while (beasts[0].kind[v] && x.indexOf(beasts[0].kind[v].q) != -1) {
  v++;
  console.log("loop");
}

答案 3 :(得分:0)

您可以测试对象是否存在。

t.FIRST_NAME,
       t.LAST_NAME,
       t.GENDER,
       t.DOB,
       subj.NAME sub_name,
       coll.NAME college_name,
       univ.NAME university_name,
       dom.name domain,
       countr.NAME country_name
TEACHER_TB t,
       SUBJECT_TB subj,
       COLLG_TCHR_TB ct,
       COLLEGE_TB coll,
       UNIVERSITY_TB univ,
       DOMAIN_TB dom,
       COUNTRY_TB countr    
where 
t.SUBJECT_ID = subj.SUBJECT_ID
       AND ct.TEACHER_ID = t.TEACHER_ID
       AND coll.COLLEGE_ID = ct.COLLEGE_ID
       AND coll.UNIVERSITY_ID = univ.UNIVERSITY_ID
       AND dom.DOMAIN_ID = coll.DOMAIN_ID
       AND countr.COUNTRY_ID = univ.COUNTRY_ID

 and t.teacher_id in(    
           SELECT t.TEACHER_ID         
           FROM TEACHER_TB t,       
           COLLG_TCHR_TB ct,
           COLLEGE_TB coll           
           WHERE     
           ct.TEACHER_ID = t.TEACHER_ID
           AND coll.COLLEGE_ID = ct.COLLEGE_ID           
           group by t.TEACHER_ID having count(coll.college_id)>1
           )