我在函数 getOlder() 中遇到下一个错误:
TypeError: Cannot read property 'age' of undefined
有什么问题以及如何解决?
function person(name, age) {
this.name=name;
this.age=age
}
// Returns the older person in a group of persons.
var getOlder = function(people) {
if (people.length === 0) {
return new person();
}
var older = people[0]; // The first one is the older for now.
var value;
for (var _ in people) {
value = people[_];
if (value.age > older.age) {
older = value;
}
}
return older;
};
// Declare some persons.
var paul = new person("Paul", 23);
var jim = new person("Jim", 24);
var sam = new person("Sam", 84);
var rob = new person("Rob", 54);
var karl = new person("Karl", 19);
var older = getOlder(paul, jim);
if (older.name !== "Jim") {
console.log("Fail");
}