循环中的Javascript数组

时间:2011-08-15 02:57:19

标签: 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("playerhash")[i].getAttribute('color');  
        break;  
    }  
}

当我尝试运行js时,它给了我Line 3: Uncaught TypeError: Cannot read property 'nodeValue' of undefined使用alert()函数我发现错误发生在i = 0时我知道至少有四个playerhash元素。 /> 如何在没有错误的情况下遍历所有元素?

2 个答案:

答案 0 :(得分:0)

.getElementsByTagName("playerhash"[i].childNodes[0].nodeValue)

你错过了)。应该是这样的:

if (getCookie('riskinfo') == xmldoc.getElementsByTagName("playerhash")[i].childNodes[0].nodeValue) {

当然,在每个循环中重复xmldoc.getElementsByTagName("playerhash")是相当昂贵的,你应该在循环之前执行一次并将结果保存在变量中。

在尝试访问该子节点之前,您还应该检查i元素是否确实存在,以及它是否实际上有任何子节点。

答案 1 :(得分:0)

正如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
  }
}