How can one implement an array of function pointers in JavaScript within their XHTML document? Today we learned in lecture how to implement JavaScript functions in an XHTML document, but what about arrays of function pointers? Can I pop a bunch of functions in an array and dereference them by index as one does in C++? Just curious...
如何在他们的XHTML文档中实现JavaScript中的函数指针数组?今天我们在讲座中学到了如何在XHTML文档中实现JavaScript函数,但是函数指针的数组呢?我可以在数组中弹出一堆函数,并像C ++一样通过索引取消引用它们吗?只是好奇...
3 个解决方案
#1
5
You can just place references to your functions in an array. For example:
您可以在数组中放置对函数的引用。例如:
function func1() { alert("foo"); }
function func2() { alert("bar"); }
function func3() { alert("baz"); }
var funcs = [ func1, func2, func3 ];
funcs[0](); // "foo"
Of course, you can just as easily use anonymous functions like this:
当然,你也可以像这样轻松使用匿名函数:
var funcs = [
function() { alert("foo"); },
function() { alert("bar"); },
function() { alert("baz"); } ];
funcs[0](); // "foo"
#2
2
There are no such things as pointers in JavaScript. Therefore there's no need "dereference". You can use functions and put them in arrays however you like:
JavaScript中没有指针这样的东西。因此,不需要“取消引用”。您可以使用函数并将它们放在数组中,但是您喜欢:
var fns = [ f1, f2, function() { console.log('!'); } ];
You can access and call them by doing:
您可以通过以下方式访问和调用它们:
fns[2]();
#3
0
If your code is looking through that array and executing those functions, you should also make sure they actually are valid functions. You can do it in pure javascript, but jQuery and other libraries have handy "isFunction" checkers that I would use for simplicity and clarity.
如果您的代码正在查看该数组并执行这些函数,那么您还应该确保它们实际上是有效的函数。你可以在纯javascript中完成它,但jQuery和其他库有方便的“isFunction”检查器,我会用它来简单明了。
#1
5
You can just place references to your functions in an array. For example:
您可以在数组中放置对函数的引用。例如:
function func1() { alert("foo"); }
function func2() { alert("bar"); }
function func3() { alert("baz"); }
var funcs = [ func1, func2, func3 ];
funcs[0](); // "foo"
Of course, you can just as easily use anonymous functions like this:
当然,你也可以像这样轻松使用匿名函数:
var funcs = [
function() { alert("foo"); },
function() { alert("bar"); },
function() { alert("baz"); } ];
funcs[0](); // "foo"
#2
2
There are no such things as pointers in JavaScript. Therefore there's no need "dereference". You can use functions and put them in arrays however you like:
JavaScript中没有指针这样的东西。因此,不需要“取消引用”。您可以使用函数并将它们放在数组中,但是您喜欢:
var fns = [ f1, f2, function() { console.log('!'); } ];
You can access and call them by doing:
您可以通过以下方式访问和调用它们:
fns[2]();
#3
0
If your code is looking through that array and executing those functions, you should also make sure they actually are valid functions. You can do it in pure javascript, but jQuery and other libraries have handy "isFunction" checkers that I would use for simplicity and clarity.
如果您的代码正在查看该数组并执行这些函数,那么您还应该确保它们实际上是有效的函数。你可以在纯javascript中完成它,但jQuery和其他库有方便的“isFunction”检查器,我会用它来简单明了。