0

I am trying to wrap my head around javascript objects and arrays. I attempted to fill and access an object as following:

obj_keys = [1,2,3,4,5,6,7];
o = {};

$.each(obj_keys, function(k, v){
    o[v] = [];
    for(var c; c < 10; c++){
        o[v][c] = [];
        o[v][c].push([11,12,13,14]);
    }
});

console.log(o); 

Object { 1: Array[10], 2: Array[10], 3: Array[10], 4: Array[10], 5: Array[10], 6: Array[10], 7: Array[10] }

console.log(o[7]);

Array [ ]

console.log(o[7][8]);

undefined

console.log(o[7][8][3]);

TypeError: o[7][8] is undefined

Why o[v] = [ ]; is OK, yet o[v][c] = [ ]; in my for(;;) loop is not?

1 Answer 1

1
for(var c; c < 10; c++){

is your problem. You don't initialise c, so it is undefined, or later NaN, and those are used as property names for adding your arrays onto o[v]. Use instead:

for(var c = 0; c < 10; c++){
Sign up to request clarification or add additional context in comments.

2 Comments

Bonus question: console.log(o[7][8][3]); returns undefined, how do I access it?
Nevermind, it should be console.log(o[7][8][0][3]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.