至少我认为在这种情况下会发生这种情况:
function MyFunc() {
var people = Array({name: 'Alex', age: 25}, {name: 'Ellen', age: 43});
for (var i=0; i<people.length; i++) {
setTimeout(function() { ShowIt(people[i].name) }, 1000); // !!!
}
}
function ShowIt(name) {
alert(name);
}
我收到此错误Uncaught TypeError: Cannot read property 'name' of undefined
,因此看起来在setTimeout
侦听器函数内部people
无法访问该变量。为什么以及如何解决?