在数组的for和if循环中包含重复项,因为计数数字太小

时间:2021-09-08 20:22:32

I'm new to javascript so any help would be greatly appreciated.

我是javascript的新手所以任何帮助将不胜感激。

What I'm trying to do is cycle through every element in the array and count the number of times the value of an element matches a given condition (even if the value is duplicated).

我要做的是循环遍历数组中的每个元素,并计算元素的值与给定条件匹配的次数(即使值是重复的)。

function loaddata(xml) {

    var count = 0;
    var i;
    var xmlDoc = xml.responseXML;
    var z = xmlDoc.getElementsByTagName("group");

    if (value1 <= value2) {
        for (i = 0; i < (0 + z.length); i++) {
            if (z[i].getElementsByTagName("name")[0].childNodes[0].nodeValue == "John") {
                count++;
            }
        }
    }
    $('#count1').html(count);
};

The count value outputted is too small. I believe the reason for this that the for loop isn't iterating through all elements in the array. When I remove the second if loop and output the count for just the for loop this value is also too small. I believe that the for loop isn't searching through the duplicate elements of the array (i.e. it is ignoring them so that they aren't then fed into the second if loop). Is it possible to specify that the for loop include duplicates?

输出的计数值太小。我认为这样做的原因是for循环不会遍历数组中的所有元素。当我删除第二个if循环并输出for循环的计数时,这个值也太小了。我相信for循环不会搜索数组的重复元素(即它忽略它们,以便它们不会被送入第二个if循环)。是否可以指定for循环包含重复项?

1 个解决方案

#1


0  

Do a console.log(z[i].getElementsByTagName("name")) and open your browser's console, and see if that array has data in it.

执行console.log(z [i] .getElementsByTagName(“name”))并打开浏览器的控制台,查看该数组中是否包含数据。

Then console.log(z[i].getElementsByTagName("name")[0].childNodes) and make sure you have nodes in it.

然后是console.log(z [i] .getElementsByTagName(“name”)[0] .childNodes)并确保其中包含节点。

Also, do you have many <group></group> tags? Because that's what you are selecting with var z = xmlDoc.getElementsByTagName("group");

此外,你有很多 标签吗?因为这是你用var z = xmlDoc.getElementsByTagName(“group”)选择的;

I hope that helps,

我希望有帮助,

#1


0  

Do a console.log(z[i].getElementsByTagName("name")) and open your browser's console, and see if that array has data in it.

执行console.log(z [i] .getElementsByTagName(“name”))并打开浏览器的控制台,查看该数组中是否包含数据。

Then console.log(z[i].getElementsByTagName("name")[0].childNodes) and make sure you have nodes in it.

然后是console.log(z [i] .getElementsByTagName(“name”)[0] .childNodes)并确保其中包含节点。

Also, do you have many <group></group> tags? Because that's what you are selecting with var z = xmlDoc.getElementsByTagName("group");

此外,你有很多 标签吗?因为这是你用var z = xmlDoc.getElementsByTagName(“group”)选择的;

I hope that helps,

我希望有帮助,