简体   繁体   English

Javascript动态创建函数列表

[英]Javascript create a list of functions dynamically

I have a piece of JavaScript code that I want to create a list of functions. 我有一段JavaScript代码,我想创建一个函数列表。 All the functions will be put in a dictionary d . 所有功能都将放入字典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: d["a"]将给我函数function() {console.log("a")}d["b"]将给我函数function() {console.log("b")}等这是我的代码:

var a = "abcdefghijklmnopqrstuvwxyz1234567890".split("");
var d = {};
for(var l = a.length, i = 0; i < l; i++)
{
    d[a[i]] = function(){console.log(a[i])};
}

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])} . 但是,当我运行上面的代码时, d["a"]d["b"]将是相同的,它们都指向function(){console.log(a[i])} How to get what I want? 如何得到我想要的?

Thanks. 谢谢。

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)
}

They don't point to the same instance of function(){console.log(a[i])} , instead, you've created a bunch of functions that all use the same reference to i . 它们没有指向function(){console.log(a[i])}的相同实例,相反,你已经创建了一堆函数,它们都使用与i相同的引用。 The value that i points at changes as the for loop executes. i指向的值随着for循环的执行而变化。

The other answers provided will work, but it involves generating twice as many functions as you need. 提供的其他答案将有效,但它涉及生成两倍于您需要的功能。

function makeLogFunction(whatToLog) {
    return function() {
        console.log(whatToLog);
    }
}

var a = "abcdefghijklmnopqrstuvwxyz1234567890";
var d = {};
for(var l = a.length, i = 0; i < l; i++) {
    d[a[i]] = makeLogFunction(a[i]);
}

Here, I have a makeLogFunction that will return a new function that always prints whatToLog . 在这里,我有一个makeLogFunction ,它将返回一个始终打印whatToLog的新函数。 The other answers will generate a new "version" of the makeLogFunction every time the loop executes. 每次循环执行时,其他答案将生成makeLogFunction的新“版本”。 For very large sets of data, this is a waste of time and memory. 对于非常大的数据集,这是浪费时间和内存。

This approach has added advantages of clarity and reusability. 这种方法增加了清晰度和可重用性的优点。 If there's a significant amount of logic happening in your loop, encapsulating it in a named function allows future reviewers to get a sense of what's going on by the name you give to the function. 如果循环中发生了大量逻辑,则将其封装在命名函数中允许将来的审阅者了解您为函数命名的内容。 You can also reuse the function in other parts of your application. 您还可以在应用程序的其他部分重用该功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM