Stack
Stack

Reputation: 348

Fill Javascript object with fixed length multidimensional array

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?

Upvotes: 0

Views: 64

Answers (1)

Bergi
Bergi

Reputation: 664395

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++){

Upvotes: 1

Related Questions