与未定义变量相关的错误

时间:2012-05-02 12:34:29

标签: javascript

这段代码有什么问题?我明白了:

TypeError:old未定义
(范围3中的10个)

但在开头定义了较旧版本: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");
    }
}

1 个答案:

答案 0 :(得分:2)

您永远不会在array[0]函数调用中定义people[0](称为older10(array)),因此较旧的设置为未定义!