jamesson
jamesson

Reputation: 327

Creating a 2d array of custom objects

The goal of the following code is to create a 2d array such that

In its current state it returns undefined, alas I am at a loss to explain why. Any suggestions about what I'm doing wrong would be greatly appreciated

var banks = []

function Clip(a,b)

{
this.track = a
this.slot = b
}

function Bank(w)

{

for (var j, j = 0; j <= 7; j++) {
    var clips = []
    var aClip = new Clip(w,j);
    //post(i)
    //post(aClip.length)
    clips[j] = aClip
}
//post();
return clips
}

function makeBanks()

{

for (var k, k = 0; k <= 7; k++) {
    var aBank = Bank(k);
    //post(i)
    //post (aClip.length)
    banks[k] = aBank
}
}

makeBanks();

console.log(banks[0][0])​

Many thanks in advance

Upvotes: 1

Views: 1663

Answers (1)

Wayne
Wayne

Reputation: 60414

Your biggest mistake is here (inside Bank):

for (var j, j = 0; j <= 7; j++) {
    var clips = []
    var aClip = new Clip(w,j);
    //post(i)
    //post(aClip.length)
    clips[j] = aClip
}

You're re-initializing clips each time through the loop, so that the only value that is retained is the last one (since the loop terminates before you get a chance to overwrite it again). To illustrate, this is what's returned from the first call to Bank:

[undefined, undefined, undefined, undefined, undefined, 
     undefined, undefined, Clip { track=0, slot=7}]

Moving the declaration outside of the loop solves this basic problem:

var clips = [];
for (var j = 0; j <= 7; j++) {
    var aClip = new Clip(w, j);
    clips[j] = aClip;
}
return clips;

Additional Clean-up

Now that we've solved the basic problem, there's a lot more we could do to clean this up:

  • Use semi-colons consistently
  • Don't name functions with an initial uppercase letter unless you intend to use them as constructors
  • Indent consistently
  • Don't rely on global variables
  • Declare and assign in one step (i.e. var j, j = 0 should be var j = 0)

The result:

function Clip(a, b) {
    this.track = a;
    this.slot = b;
}

function makeBank(w) {
    var clips = [];
    for (var j = 0; j <= 7; j++) {
        var aClip = new Clip(w, j);
        clips[j] = aClip;
    }
    return clips;
}

function makeBanks() {
    var banks = [];
    for (var k = 0; k <= 7; k++) {
        var aBank = makeBank(k);
        banks[k] = aBank;
    }
    return banks;
}

var banks = makeBanks();
console.log(banks[0][0]);

Upvotes: 3

Related Questions