Squirtle
Squirtle

Reputation: 169

Javascript indexing array issue

Hi I have an array that hold the following numbers, however when I loop though the eachNode function(which iterates 13 times) it repeats all the list elements 13 times. I tested everything but it still produces an error, I'm I executing the for loop correctly?

list[61,67,78]
var len = list.length;

fd.graph.eachNode(function (node) { // loops thru all node id's in graph (13)
    for (var i = 0; i < len; ++i) {
        if (i in list) {
            var nody = list[i]; // I put the number in a variable
            var nodess = fd.graph.getNode(nody); //this takes the number and matches it with a node id, it "odjectify" it
            if (node.id != nodess.id) { //  if the list nodes are not the same
                node.setData('alpha', 0); //
                node.eachAdjacency(function (adj) { // this make the unmatched nodes disappear
                    adj.setData('alpha', 0, 'end');
                });
            }
        }
    }
});

Upvotes: 0

Views: 83

Answers (2)

David G
David G

Reputation: 96810

This line is unneeded:

if (i in list)

The in keyword returns true if its right operand contains the property specified by its left operand. When using this with arrays, it returns unexpected results. The behavior of this keyword is insignificant in this context, so you should simply take it out.

Moreover, you need to create the list array like this:

var list = [61, 67, 78];

...however, when I loop though eachNode (which iterates 13 times) it repeats all the list elements 13 times

It doesn't, it in fact iterates over eachNode 13 times. You also made a for loop which will traverse the list array by its length.


Now that you've given me more detail as to what you want, here is the updated code. I hope it works for you:

fd.graph.eachNode(function (node) {
    var flag = false;

    for (var i = 0; i < len; ++i)
    {
        var nody = list[i];
        var nodess = fd.graph.getNode(nody);

        if (node.id == nodess.id) {
            flag = true; break;
        }
    }

    if (flag)
    {
        node.setData('alpha', 0);
        node.eachAdjacency(function (adj) {
           adj.setData('alpha', 0, 'end');
        });
    }
});

Upvotes: 1

Kenneth
Kenneth

Reputation: 28737

This is the behavior by design:

You loop over the graph (13 times as you say), then inside each iteration you loop over your array (3 items).

If you only want to loop once over your array, just move it out of the outer loop

Upvotes: 0

Related Questions