当我用下面的函数解析这个对象时,我在表中得到的第一个值是“undefined”。知道为什么会这样吗?我解析不正确吗?我应该使用不同的循环吗?
var students = [
{
fn : "Stone",
ln : "Carpenter",
scores : [61,99,73,68,80,62,176,78]
},
{
fn : "Samson",
ln : "Sears",
scores : [68,193,91,190,95,65,171,75]
},
{
fn : "Quin",
ln : "Morton",
scores : [79,95,161,92,182,163,198,182]
},
{
fn : "Qunitessa",
ln : "Hardy",
scores : [99,65,75,69,77,67,86,78]
},
{
fn : "Ashley",
ln : "England",
scores : [147,70,81,64,148,71,70,63]
},
{
fn : "Thaddeus",
ln : "Hutchinson",
scores : [99,190,188,185,160,88,89,76]
},
{
fn : "Yeo",
ln : "Hayes",
scores : [88,64,199,165,198,76,74,81]
},
{
fn : "Rylee",
ln : "Larson",
scores : [71,126,63,71,168,173,175,88]
}
];
function updateTable(obj) {
var rows,
len;
len = obj.length;
rows = "<table>"
rows += "<tbody>"
for (var i in obj) {
var scoreLen,
score,
sum;
scoreLen = obj[i].scores.length;
scores = obj[i].scores;
rows += "<tr>"
rows += "<td>" + obj[i].fn + "</td>"
rows += "<td>" + obj[i].ln + "</td>"
for(j=0; j<scoreLen; j+=1) {
rows += "<td>" + scores[j] + "</td>"
}
rows += "<td>" + arraySum(obj[i].scores) + "</td>"
rows += "</tr>"
}
document.getElementsByTagName('body')[0].innerHTML = rows
console.log(rows)
}
答案 0 :(得分:2)
这将迭代除length
之类的数组元素之外的数组属性。你应该使用这样的for循环迭代:
for(var i = 0; i < students.length; i++) {
...
}
答案 1 :(得分:2)
以下是updateTable
函数的正确实现。 students
是一个对象数组,但您尝试将其作为对象的对象进行访问。这就是未定义的原因。
var students = [{obj1:stuff}, {obj2:stuff}, ... ,{objn:stuff}]
students[0] returns {obj1:stuff}, students[1] returns {obj2:stuff}
等等。
function updateTable(arr) {
var rows,
len;
len = arr.length;
rows = "<table>"
rows += "<tbody>"
for (var i =0; i< len; i++) {
var scoreLen,
score,
sum;
scoreLen = arr[i].scores.length;
scores = arr[i].scores;
rows += "<tr>"
rows += "<td>" + arr[i].fn + "</td>"
rows += "<td>" + arr[i].ln + "</td>"
for(j=0; j<scoreLen; j+=1) {
rows += "<td>" + scores[j] + "</td>"
}
rows += "<td>" + arraySum(arr[i].scores) + "</td>"
rows += "</tr>"
}
document.getElementsByTagName('body')[0].innerHTML = rows
console.log(rows)
}
答案 2 :(得分:0)
迭代数组中的项目时,请勿使用for .. in
。相反,始终使用数字循环,例如:
for (var i=0, len=myArray.length; i<len; ++i){ … }
或者如果你想以较少的输入从后向前迭代:
for (var i=myArray.length;i--;){ … }