Javascript:for 循环中定义的每个事件处理程序都是相同的,使用最后一次迭代的值 [英] Javascript: every event-handler defined in for-loop is the same, uses last iteration's values

查看:37
本文介绍了Javascript:for 循环中定义的每个事件处理程序都是相同的,使用最后一次迭代的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解 Javascript 中的范围规则.

I have trouble understanding the scoping rules in Javascript.

在下面的示例中,我假设范围 url 变量在 for 循环中是私有的.并且 onload-event 函数会看到这个私有实例.

In the example below, I would assume that scope url variable is private in the for-loop. And that the onload-event function would see this private instance.

但事情似乎并非如此 - 警报会弹出最后一个网址两次.

But things does not seems work like that - the alert will popup with the last url twice.

如果有人能澄清发生了什么,我将不胜感激.

If somebody can clarify what is going on, I'll be grateful.

<html>
<head>
</head>
<body>
<script type="text/javascript">
    var testArray = ["http://g0.gstatic.com/images/icons/onebox/weather_rain-40.png", "http://g0.gstatic.com/images/icons/onebox/weather_scatteredshowers-40.png"];
    for (var i=0;i<testArray.length;i++){
        var img = new Image();
        var url = testArray[i];
        img.onload = function(){
            alert(url);
        }
        img.src = url;
    }
</script>
</body>
</html>

推荐答案

Javascript 不是块作用域,因此每次需要新作用域时都需要一个新函数.请参阅 patrick dw 的回答.

Javascript is not block-scoped, and thus requires a new function every time you want a new scope. See the answer by patrick dw.

这就是为什么使用 [].map(function(x){...})[].forEach(function(x){...}) 在 javascript 标准中,因为无论如何您都需要定义这些函数.

This is why it is advantageous to use [].map(function(x){...}) or [].forEach(function(x){...}) which are in the javascript standard, since you'll need to define those functions anyway.

var imageArray = urlArray.map(function(url) {
    var image = new Image();
    image.src = url;
    image.onload = function() {
        alert(url);
    };

    return image;
});

这篇关于Javascript:for 循环中定义的每个事件处理程序都是相同的,使用最后一次迭代的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆