我可以存储JavaScript函数在数组中? [英] Can I store JavaScript Functions in arrays?

查看:99
本文介绍了我可以存储JavaScript函数在数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何能存储功能与命名属性数组,这样我就可以调用诸如

How can I store functions in an Array with named properties, so I can call like

FunctionArray["DoThis"]

甚至

FunctionArray[integer]


注意:我不希望使用评估

推荐答案

要记住的重要事情是,函数是JavaScript中的第一类对象。所以,你可以通过他们周围作为参数,把它们作为对象值等。值(S)在阵列是只是一个例子。

The important thing to remember is that functions are first class objects in JavaScript. So you can pass them around as parameters, use them as object values and so on. Value(s) in an array are just one example of that.

请注意,我们并没有存储功能于一身的阵列虽然我们可以做到这一点,并用数字索引访问它们。我们将它们存储在由我们要访问该功能名为键入一个普通的对象。

Note that we are not storing the functions in an array although we can do that and access them with a numeric index. We are storing them in a regular object keyed by the name we want to access that function with.

var functions = {
    blah: function() { alert("blah"); },
    foo: function() { console.log("foo"); }
};

呼叫作为

functions.blah();

functions["blah"]();

这篇关于我可以存储JavaScript函数在数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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