3

我在函数 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");
}
4

2 回答 2

5

查看函数的签名:

var getOlder = function(people) {

您没有创建函数以使其接受两个人对象。您显然只接受一个数组,因为您正在使用people.lengthpeople[0]在函数内部。所以你还必须传递一个数组:

var older = getOlder([paul, jim]);
于 2012-10-21T10:10:13.247 回答
1
var getOlder = function() {
    var people = arguments;
    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;
   };

通过在函数定义中不接受任何参数并依靠 JS 的可变参数功能,您可以摆脱调用getOlder(paul, jim).

arguments是每个函数的属性,它基本上是在调用时提供给它的变量参数数组。

于 2012-10-21T10:29:08.163 回答