1

这段代码有什么问题?我得到:

TypeError: old is undefined
(10 out of range 3)

但老是在开头定义:var older = people[0]

function person(name, age) {
    this.name=name;
    this.age=age
}

function foo() {
    var older10 = function(people) {
        var older = people[0];

        for (var index = 1; index < 10; index++) {
            if (people[index].age > older.age) {
                older = people[index]; // error here
            }
        }
        return older;
    };

    var array = [];
    array[1] = new person("Paul", 23);
    array[2] = new person("Jim", 24);
    array[3] = new person("Sam", 84);
    array[4] = new person("Rob", 54);
    array[8] = new person("Karl", 19);
    array[9] = new person("", 0);

    var older = older10(array);

    if (older.name === "Sam") {
        console.log("ok");
    }
}
4

1 回答 1

2

您从不定义array[0]people[0]older10(array)函数调用中称为),因此将 old 设置为未定义!

于 2012-05-02T12:36:38.347 回答