循环中的Javascript数组
我试图通过javascript循环遍历名为playerhash的xml文件中的所有元素循环中的Javascript数组,javascript,xml,Javascript,Xml,我试图通过javascript循环遍历名为playerhash的xml文件中的所有元素 for(var i = 0; i < 4; i++) { alert(i); if(getCookie('riskinfo') == xmldoc.getElementsByTagName("playerhash"[i].childNodes[0].nodeValue) { player = xmldoc.getElementsByTagName("playe
for(var i = 0; i < 4; i++) {
alert(i);
if(getCookie('riskinfo') == xmldoc.getElementsByTagName("playerhash"[i].childNodes[0].nodeValue) {
player = xmldoc.getElementsByTagName("playerhash")[i].getAttribute('color');
break;
}
}
当我尝试运行js时,它给了我第3行:UncaughtTypeError:无法使用警报函数读取undefined的属性'nodeValue',我发现错误发生在I=0时,并且我知道至少有四个playerhash元素。
如何在没有错误的情况下循环所有元素
.getElementsByTagName("playerhash"[i].childNodes[0].nodeValue)
你少了一个。应该是这样的:
if (getCookie('riskinfo') == xmldoc.getElementsByTagName("playerhash")[i].childNodes[0].nodeValue) {
当然,在每个循环中重复xmldoc.getElementsByTagNameplayerhash是相当昂贵的,您应该在循环之前执行一次,并将结果保存在变量中
在尝试访问子节点之前,您可能还应该检查第i个元素是否确实存在,以及它是否确实有任何子节点。正如deceze所说,代码中存在错误。您应该以更小的步骤编写代码,以便更容易调试。此外,在继续之前检查每个步骤,以便在意外失败时不会向用户抛出错误。条件表达式不应执行赋值操作,因为这会使调试更加困难,请仅将其用于测试条件:
// Should have already checked that xmldoc is a valid document
var riskinfo = getCookie('riskinfo');
var playerhash = xmldoc.getElementsByTagName("playerhash");
var max = 4; // or playerhash.length
var node, player;
for(var i = 0; i < max; i++) {
node = playerhash[i];
if (node && node.nodeValue == riskinfo) {
player = node.getAttribute('color');
i = max; // break out of for loop
}
}
这意味着一个或多个玩家没有孩子。或者增加一些检查,或者确保他们都有孩子。谢谢你的编码提示。我对javascript和xml非常陌生,因此非常感谢您的帮助。如果可能的话,保持语句简洁总是一个好主意。虽然它有更多的代码,但并不影响速度。通常,它越快,越容易理解,越容易调试和维护。通常,经验最差的程序员需要维护,所以要让他们的生活可以忍受-