user11604311
user11604311

Reputation: 1

Cannot operate with array as array

I'm creating an array like this

var p1_s1 = {
            'title': 'p1_s1', 'titleDisplayed': 'p1_s1', 'type': 'numbers', 'page':1,'strings': 1, 'length': 7, 'placeholder':'0000000', 'painted':'black', 'notPainted':'#ffe485', 'left':410, 'top':161, 'width':394, 'height':144,
            'ids':[
                    ['path5472','path5440','path5488','path5520','path5504','path5456','path5536'],
                    ['path5360','path5328','path5376','path5408','path5392','path5344','path5424'],
                    ['path5584','path5552','path5600','path5632','path5616','path5568','path5648'],
                    ['path4912','path4880','path4928','path4960','path4944','path4896','path4976'],
                    ['path5024','path4992','path5040','path5072','path5056','path5008','path5088'],
                    ['path5136','path5104','path5152','path5184','path5168','path5120','path5200'],
                    ['path5248','path5216','path5264','path5296','path5280','path5232','path5312']
                    ]
    };

Then, in script code i call this variable

...
var ids = p1_s1['ids'];
        for(var i = ids.length;i>=0;i--)
        {
            drawOneNumber( ids[i], parseInt(value[i]) );
        }
...
function drawOneNumber( place, number )
{
    number = numberToSegments( number );
    console.log(place);
    for(var i=0;i<number.length;i++)
    {
        console.log( place[i] );
    }
    ...
}

On string console.log(place); i see array in console as it should be.

(7) […]
​0: "path5248"
​1: "path5216"
​2: "path5264"
​3: "path5296"
​4: "path5280"
​5: "path5232"
​6: "path5312"
​length: 7
​

But on string console.log( place[i] ); I got an error

TypeError: place is undefined

Same situation with

place.forEach(element => console.log(element));

Code Array.isArray(place); returns true, but I cannot manipulate this variable lika an array. What am I doing wrong? Thank you.

Upvotes: -1

Views: 68

Answers (1)

Maxime Girou
Maxime Girou

Reputation: 1570

The problem come from the for loop

You defined If you array is a length of 5, the last element will be accesible at the 4th place.

As you defined i = ids.length and try to access ids[i], it will be undefined and the variable placein your drawOneNumber function will be undefined too.

Example:

const arr = ["foo", "bar", "youhou"];

console.log(arr.length);
console.log(arr[arr.length]);

Try : for(var i = ids.length -1 ;i>=0;i--) instead.

Upvotes: 3

Related Questions