我创建了3个对象,它们相互嵌套数组-我们将它们称为表,行和列,以便向您展示问题所在。表有一个行数组,行有一个列数组。当我从表中调用行的属性时,没问题。当我从行调用列的属性时,它说未定义,但是在调试器和控制台中,它可以识别对象及其属性。也许我盯着它看了太久,但看不到根本的区别。
我剥离了Table层,以确保它与嵌套对象无关。这是代码,不起作用:
function Column()
{
this.sampleProp = "testprop";
this.content = "<td>sometext</td>";
}
function Row(columns)
{
this.columns = [];
this.columns = columns;
this.outputRows = function()
{
var temp = "<tr>";
for(var i = 0; i < this.columns.length; i++)
{
//this is the line that doesn't work and comes out as undefined:
temp += this.columns[i].content;
console.log("Problem: " + this.columns[i].content);
//yet the object exists, and has the correct properties:
console.log(this.columns[i]);
}
temp += "</tr>";
return temp;
};
}
function test()
{
var col = new Column();
console.log("Printing out the value from here works fine: " + col.content);
var cols = [col];
console.log("It's also fine when it's called from an array: " + cols[0].content);
var row = new Row([cols]);
console.log(row.outputRows());
}
这是父层和行之间的交互,可以正常工作:
function Table(rows)
{
this.rows = [];
this.rows = rows;
this.outputTable = function()
{
var temp = "<table>";
for(var i = 0; i < this.rows.length; i++)
{
temp += this.rows[i].outputRows();
}
temp += "</table>";
return temp;
};
}
和更新的测试功能:
function test()
{
var column = new Column();
var cols = [column];
var row = new Row([cols]);
console.log(row.outputRows());
var rs = [row, row];
var table = new Table(rs);
console.log(table.outputTable());
}
以这种方式打印出两行,每行内部未定义。我最初将column.content编写为一个函数,但没有区别。
请告诉我我在这里错过了哪些愚蠢的错误!
答案 0 :(得分:0)
更改该行:
var row = new Row([cols])
进入
var row = new Row(cols)
由于cols已经是数组,因此您无需再次将其放入数组。
function Column() {
this.sampleProp = "testprop";
this.content = "<td>sometext</td>";
}
function Row(columns) {
// removed this.columns = [] since you are assigning it in the next line
this.columns = columns;
this.outputRows = function() {
var temp = "<tr>";
for (var i = 0; i < this.columns.length; i++) {
//this is the line that doesn't work and comes out as undefined:
temp += this.columns[i].content;
}
temp += "</tr>";
return temp;
};
}
function test() {
var col = new Column()
console.log("Printing out the value from here works fine: " + col.content);
var cols = [col];
console.log("It's also fine when it's called from an array: " + cols[0].content);
var row = new Row(cols); // the problem was here
console.log(row.outputRows());
}
test()