Javascript动态创建函数列表 [英] Javascript create a list of functions dynamically

查看:89
本文介绍了Javascript动态创建函数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段 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屋!

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