我试图在 Javascript 的 for 循环内执行 setTimeout() 函数,但我收到错误“shape is undefined”,即使它已定义,我将其作为参数传递给setTimeout() 调用中的函数。如果我删除 setTimeout 附件,该函数就可以正常工作。
为什么会出现此错误,我该如何解决?
谢谢!
function fadeShapes(layer, movement, opacity, speed) {
var shapes = layer.getChildren();
for(var n = 0; n < shapes.length; n++) {
var shape = layer.getChildren()[n];
setTimeout(function(shape){
shape.transitionTo({
alpha: opacity,
duration: speed
});
}, 100);
}
}
最佳答案
JavaScript 没有 block 作用域,因此您所有的超时函数都指向同一个变量 shape
,该变量在循环结束后指向数组的未定义索引。您可以使用匿名函数来模拟您正在寻找的范围:
for(var n = 0; n < shapes.length; n++) {
var shape = shapes[n]; //Use shapes so you aren't invoking the function over and over
setTimeout((function(s){
return function() { //rename shape to s in the new scope.
s.transitionTo({
alpha: opacity,
duration: speed
});
};
})(shape), 100);
}
正如您从我的括号匹配问题中看出的那样,这可能有点棘手。这可以用 ES5 的 Array.forEach
清除。 :
layer.getChildren().forEach(function(shape) { //each element of the array gets passed individually to the function
setTimeout(function(shape){
shape.transitionTo({
alpha: opacity,
duration: speed
});
}, 100);
});
forEach
内置于现代浏览器中,但可以在 Internet Explorer 旧版浏览器中填充。
关于Javascript 将参数传递给循环内的 setTimeout 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11821214/