Javascript动态创建函数列表 [英] Javascript create a list of functions dynamically
问题描述
我有一段 JavaScript
代码,我想创建一个函数列表。所有函数都将放在字典 d
中。 d [a]
会给我函数 function(){console.log(a)}
和 d [b]
将给我函数 function(){console.log(b)}
等。这是我的代码:
I have a piece of JavaScript
code that I want to create a list of functions. All the functions will be put in a dictionary d
. d["a"]
will give me the function function() {console.log("a")}
and d["b"]
will give me the function function() {console.log("b")}
etc. This is my code:
var a = "abcdefghijklmnopqrstuvwxyz1234567890".split("");
var d = {};
for(var l = a.length, i = 0; i < l; i++)
{
d[a[i]] = function(){console.log(a[i])};
}
但是,当我运行上面的代码时, d [a]
和 d [b]
将是相同的,它们都指向 function() {的console.log(A [1])}
。如何得到我想要的东西?
However, when I run the above code, d["a"]
and d["b"]
will be the same, they all point to function(){console.log(a[i])}
. How to get what I want?
谢谢。
推荐答案
你需要给函数的每个实例赋予它自己的变量:
You need to give each instance of the function its own variable:
for(var l = a.length, i = 0; i < l; i++)
{
(function (x) {
d[a[x]] = function(){console.log(a[x])};
})(i)
}
这篇关于Javascript动态创建函数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!