以下代码的目标是创建一个二维数组,使其
在当前状态下,它返回undefined,唉,我无法解释原因。任何关于我做错的建议都将不胜感激
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])
非常感谢提前
答案 0 :(得分:3)
你最大的错误就在这里(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
}
每次循环都会重新初始化clips
,因此唯一保留的值是最后一个(因为循环在你有机会再次覆盖它之前终止)。为了说明这一点,这是第一次调用Bank
时返回的内容:
[undefined, undefined, undefined, undefined, undefined,
undefined, undefined, Clip { track=0, slot=7}]
在循环之外移动声明解决了这个基本问题:
var clips = [];
for (var j = 0; j <= 7; j++) {
var aClip = new Clip(w, j);
clips[j] = aClip;
}
return clips;
现在我们已经解决了基本问题,我们可以做更多的事情来清理它:
var j, j = 0
应为var j = 0
)结果:
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]);