我可以在数组中存储 JavaScript 函数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3592468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:21:04  来源:igfitidea点击:

Can I store JavaScript Functions in arrays?

javascriptarraysfunction

提问by Emre

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

如何将函数存储在具有命名属性的数组中,以便我可以调用

FunctionArray["DoThis"]

or even

甚至

FunctionArray[integer]


Note:I do not wish to use eval.

注意:我不想使用eval.

回答by Anurag

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.

需要记住的重要一点是,函数是 JavaScript 中的第一类对象。因此,您可以将它们作为参数传递,将它们用作对象值等等。数组中的值只是其中一个示例。

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

call as

称为

functions.blah();

or

或者

functions["blah"]();

回答by meder omuraliev

You want an object literal, not an array.

你想要一个对象文字,而不是一个数组。

x = { 'dothis': function() { alert('hi'); } };

Object

目的

x['dothis']()

You can also dynamically invoke

也可以动态调用

y = 'dothis';
x[y]()

Static/hard coded invocation:

静态/硬编码调用:

x.dothis()

If you do want an array though:

如果你确实想要一个数组:

x = [function(){alert('hi');}][0]()

回答by Fillipe Ogg

you can actually do that, just declare it outside the array, like so...

你实际上可以做到这一点,只需在数组外声明它,就像这样......

const your_function = function(){ console.log( "I am your function" ) }

const group = [ 0, "lizard", false, your_function() ]

group[ 3 ]

you may also change where it's called, if you want to...

你也可以改变它的名字,如果你想......

const your_function = function(){ console.log( "I am your function" ) }

const group = [ 0, "lizard", false, your_function ]

group[ 3 ]()

EDIT: functions were named wrong :/ sry

编辑:函数命名错误:/ sry

回答by BrunoLM

You can access a object's properties through it's name (x["A"]), if you want to assign indexes (0 = "A") you have to do this, here is a example. (I'm not sure if the forloop will work on any browser, I've tested on Firefox, but you can get the idea)

您可以通过对象的名称 (x["A"]) 访问对象的属性,如果要分配索引 (0 = "A"),则必须执行此操作,这是一个示例。(我不确定for循环是否适用于任何浏览器,我已经在 Firefox 上进行了测试,但您可以理解)

var x = {};

x.A = function() { alert("func 1"); };
x.B = function() { alert("func 2"); };


var i = 0;
for (a in x)
{
    x[i] = x[a];
    ++i;
}


x[0](); // func 1
x[1](); // func 2
x["A"](); // func 1
x["B"](); // func 2

回答by Dmitry Masley

You even can use function as name of the property:

您甚至可以使用函数作为属性的名称:

var func = function(a, b){alert(a+b)};
var obj = {};
obj[func] = 2;

回答by Trey Brister

Here is an array that contains various data types including a function.

这是一个包含各种数据类型(包括函数)的数组。

Although there is an object in this example, the function is not within the object.

虽然在这个例子中有一个对象,但函数并不在对象内。

If you replace this object with a string the function will still work as planned.

如果您用字符串替换此对象,该函数仍将按计划工作。

I can call the function from within or without the array.

我可以从数组内部或外部调用该函数。

myArray = [
        1,
        true,
        "String",
        {
            name: "trey",
            age: 43,
        },
        [1,2,3,4],
        myFunction = function(){
            console.log("whats up!");
        },
        myArray[5](),
    ];
    console.log(myArray);
    myArray[5]();

Here is the output:

这是输出:

whats up!
[ 1, true, 'String', { name: 'trey', age: 43 }, [ 1, 2, 3, 4 ], [Function], undefined ]
whats up!

回答by Arshad

Basically function is a special type of Object in javascript. And in javascript, in array you can store anything (Not necessarily of the same type). So going by this, yes ! you can store a function, object, primitive values in an array in javascript.

基本上函数是javascript中一种特殊类型的对象。在 javascript 中,您可以在数组中存储任何内容(不一定是相同类型)。所以通过这个,是的!您可以在 javascript 中的数组中存储函数、对象、原始值。

var arr = ["hello",true,false, 1, {name: "arshad"}, function(){}]

And you can mix object and function to make the named function like:

您可以混合使用对象和函数来创建命名函数,例如:

{ callBythisname: function(){ .... }}

You can store this object in an array as well

您也可以将此对象存储在数组中

var arr = [{ callBythisname: function(){ .... }}];

If you want to call it, call like:

如果你想调用它,调用如下:

arr[0].callBythisname();

回答by Nick Craver

You can store things directly in an array, but as an object, for example:

您可以将事物直接存储在数组中,但作为对象,例如:

var Functions = { DoThis: function() { alert("do this"); } };

Functions['DoThis'](); //alerts "do this"
Functions.DoThis()     //alerts "do this"

You can give it a try here.

你可以在这里试一试