Reputation: 327
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
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;
Now that we've solved the basic problem, there's a lot more we could do to clean this up:
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