我试图通过循环遍历对象数组来创建一个带有jQuery的简单表,但是在控制台中获取此消息:
TypeError: 'undefined' is not an object (evaluating 'people[i].lastName')
如果我定义特定对象(即John.lastName)但不使用array[i]
,它是否有效,我做错了什么?
var person = function(firstName, lastName) {
this.firstName = firstName || "Anonymous";
this.lastName = lastName || "Anonymous";
};
var John = new person("John", "Walter");
var Bob = new person("Bob", "Stevens");
var Gerry = new person("Gerry", "Cricket");
var Frank = new person("Frank", "Bloom");
var people = [John, Bob, Gerry, Frank];
for (i = 0; i < people.length; i++) {
$(document).ready(function() {
$("body").append("<table><tr><td>" + people[i].lastName + "</td></tr></table>");
});
};
答案 0 :(得分:1)
You can't put a $(document).ready within a for loop. Put your function inside the document.ready and your code works fine. To Add a table before the for loop and the /table
after the for loop to prevent making each row in the array a table.
$(document).ready(function()
{
var person = function(firstName, lastName) {
this.firstName = firstName || "Anonymous";
this.lastName = lastName || "Anonymous";
};
var John = new person("John", "Walter");
var Bob = new person("Bob", "Stevens");
var Gerry = new person("Gerry", "Cricket");
var Frank = new person("Frank", "Bloom");
var people = [John, Bob, Gerry, Frank];
$("body").append("<table>");
for (i = 0; i < people.length; i++) {
console.log(people[i]);
$("table").append("<tr><td>" + people[i].lastName + "</td></tr>");
};
$("<table>").append("</table>");
});