在循环中向javascript的数组添加函数 [英] Adding functions to javascript's array in a loop

查看:76
本文介绍了在循环中向javascript的数组添加函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在循环中创建具有函数的数组。但我认为没有关于封装的东西。

I'm try to creat array with functions in a loop. But I think don't get something about encapsulation.

例如,此代码返回y y。 现场演示

For example this code returns "y y". Live demo.

HTML

<div id="result"></div>

Javascript

var json = {
            '1':'x',
            '2':'y'
           };
var my_array = [];
var div = document.getElementById('result');

for (var key in json) {
    my_array.push(function() { 
        div.innerHTML = div.innerHTML + ' ' + json[key];
    });
};

var length = my_array.length;

for (var i = 0; i < length; i++) {
  my_function = my_array[i];
  my_function();
}

我该怎么办才能获得xy?

What should I do to get "x y"?

Tnx很多。

推荐答案

这是由于闭包在JavaScript中的工作方式。

This is due to the way closures work in JavaScript.

你想要这样的东西:

for (var key in json) {
    (function(key) {
        my_array.push(function() { 
            div.innerHTML = div.innerHTML + ' ' + json[key];
        });
    })(key);
}

在JavaScript中,闭包或匿名函数在词法上绑定到它们的作用域定义。这意味着他们可以访问已在 定义的闭包范围内定义的所有变量。

In JavaScript, closures or anonymous functions are lexically bound to the scope in which they are defined. What this means is that they have access to all variables that have been defined in the scope in which the closure is also defined.

所以在你的原始代码,你有 key ,它最初指向 1 。在你的函数中,你有 json [key] ,最初是 json [1] ,这是 X 。然后当循环进入下一次迭代时,你将 key 设置为 2 。但问题是第一个函数实例中的 key ,第二个函数实例都指向同一个位置。因此,当您最终评估该函数时,它们将在执行时使用 key 具有的任何值。在执行时,设置为 2 ,因为这是的最后一个值在循环结束时键

So in your original code, you have key, which initially points to 1. In your function, you have json[key], which originally is json[1], which is x. Then when the loop goes to the next iteration you have key set to 2. But the thing is that key in the first function instance and the second function instance both point to the same location. So when you finally evaluate the function, they will use whatever value key has at the time of execution. At the time of execution, key is set to 2 because that was the last value of key at the end of the loop.

要解决此问题,您必须使用匿名的自调用函数引入新范围。通过使用此模式,您故意引入 new 范围,以便此新范围中的 key 具有自己的位置,并且与<$ c $不同外部范围内的c> key 。

To fix this, you have to introduce a new scope by using an anonymous, self-invoked function. By using this pattern, you deliberately introduce a new scope such that key in this new scope has its own location and is different from key in the outer scope.

查看更新的小提琴

这篇关于在循环中向javascript的数组添加函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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