此代码有什么问题?我得到:
TypeError:未定义较旧
(范围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");
}
}
最佳答案
您永远不会定义array[0]
(在people[0]
函数调用中称为older10(array)
),因此将old设置为undefined!
关于javascript - 与 undefined variable 有关的错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10413854/