[英]Javascript Updating 'global' array with value from within a function
Yesterday, I needed help & was introduced to Closures (Im still struggling with that one). 昨天,我需要帮助并被介绍给Closures(我仍在努力解决该问题)。
At the start of the function, I created arrays, which need to be populated with values as created within the child function. 在函数开始时,我创建了数组,需要使用在子函数中创建的值填充数组。 I had an understanding that 'return' would simply return the values & update the array magically, apparently it doesnt happen that way.
我的理解是,“ return”将简单地返回值并神奇地更新数组,显然这不会发生。 I tried push as well but again, no magic.
我也尝试过推,但再次,没有魔力。
eEndDesigning.onclick = publicity;
function publicity() {
var eCamerasArray = $(".cCameras").toArray();
// this is the array that needs to be updated with the annon. func. inside setTimeout func.
var iLeftPosArray = [];
// this is the second array that needs to be updated
var iTopPosArray = [];
for (var i = 0; i < eCamerasArray.length; i++) {
var timer = Math.floor(Math.random() * 300) + 100;
(function(i) // a closure function
{
window.setTimeout(function() {
// following two values are the ones that need to be fed back to 'global' arrays
iLeftPosArray[i] = Math.floor(Math.random() * 139) + 360;
iTopPosArray[i] = Math.floor(Math.random() * 160) + 100;
$(eCamerasArray[i]).animate({
left: iLeftPosArray[i] + "px",
top: iTopPosArray[i] + "px"
}, 100, "linear");
return [iLeftPosArray[i], iTopPosArray[i]];
}, timer);
}(i));
}
}
您可能需要将数组iLeftPosArray
和iTopPosArray
一个级别,因为它们当前不是全局的,但是具有函数的作用域。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.