-1

i have a problem accessing an array within an object method. While the log returns the value perfectly, the following line returns an error that allRect[n] is undefined.

I suppose it has something to do with variable accessibility, but the fact that it can be logged in one line and refuses it's existence in the next one leaves me a bit out of ideas.

Thanks all.

        this.s = Snap('#'+id);
        var allRects = [];

        this.xPos = 0;
        var scale = vizWidth/locationSum(data);         

        ...


        //methods
        this.updateViz = function() {

            apiRequest('datasets', 164, 'json').done(   

                function(data){ 
                    var n = 0;


                    data = locationDataIntoArray(data);


                    for(i = 0; i< allRects.length; i++){
                        console.log(allRects[n]);

                        allRects[n].animate({ width:parseInt(data[i][2]), opacity:evaluateMachine(data[i][0])},3000);
                        n++;
                        allRects[n].animate({ width:parseInt(data[i][3]), opacity:evaluateTech(data[i][1])},3000);
                        n++;                
                    }

                }       
            )
        };

1 Answers1

0

In this code:

                for(i = 0; i< allRects.length; i++){
                    console.log(allRects[n]);

                    allRects[n].animate({ width:parseInt(data[i][2]), opacity:evaluateMachine(data[i][0])},3000);
                    n++;
                    allRects[n].animate({ width:parseInt(data[i][3]), opacity:evaluateTech(data[i][1])},3000);
                    n++;                
                }

you're incrementing n twice on each iteration. Halfway through the for loop, n will be beyond the end of the array.

The first time through the loop, when i and n are both zero, you'll animate allRects[0]. Then you increment n and animate allRects[1], and then increment n again. Thus, on the second time through the loop, you'll be animating allRects[2] and allRects[3], and so on.

Pointy
  • 405,095
  • 59
  • 585
  • 614