Firing named functions from an array with JavaScript?
I'm very new to JavaScript, but this topic seems to have attracted only scant forum attention. Given a number of simple functions:
function do_something(){...};
function do_somemore(){...};
function do_something_else(){...};
I was expecting to be able to assign these explicitly to cells in an (here 2D) array.
myMatrix[5][3] = do_something();
myMatrix[5][4] = do_somemore();
myMatrix[5][5] = do_something_else();
The reason I want to use such an approach are :
- simple to understand and maintain.
- eliminates potentially redundant anonymous function assignments in the array.
any given function can be assigned to multiple array cells, for example:
myMatrix[2][6] = do_somemore(); myMatrix[5][4] = do_somemore(); myMatrix[6][3] = do_somemore();
Unfortunately, calls such as the following (based on various forum examples, plus a little "suck it and see") are all failing.
x = myMatrix[5][4]do_somemore(); -> "missing ; before statement"
x = (myMatrix[5][4])do开发者_JAVA百科_somemore(); -> "missing ; before statement"
x = (myMatrix[5][4]do_somemore)(); -> "missing ) in parenthetical"
x = (myMatrix[5][4])(do_somemore()); -> "is not a function"
x = (myMatrix[5][4])()do_somemore(); -> "missing ; before statement"
x = myMatrix[5][4]()do_somemore(); -> "missing ; before statement"
x = myMatrix[5][4](); -> "is not a function"
x = (myMatrix[5][4])(); -> "is not a function"
As I have no knowledge of JavaScript internals, I'd be glad of suggestions how to get the function calls firing.
You should assign them like this:
myMatrix[5][3] = do_something;
myMatrix[5][3] = do_something;
Your way would set the value to the RESULT of the function!
I'm not entirely clear about what you are after, but:
First, before you can assign a value to an array, that array has to exist:
var myMatrix = [];
myMatrix[5] = [];
myMatrix[5][3] = … // Then you can assign something
Then, if you want to assign the return value of a function:
myMatrix[5][3] = do_something();
Or, if you want to assign the function itself:
myMatrix[5][3] = do_something;
… and then call it and assign its return value to x
:
var x = myMatrix[5][3]();
… which is the same as var x = do_something()
except that inside the function this
will be myMatrix[5]
instead of window
.
myMatrix[5][3] = do_something;
myMatrix[5][4] = do_somemore;
myMatrix[5][5] = do_something_else;
var x = myMatrix[5][3]();
var y = myMatrix[5][4]();
var z = myMatrix[5][5]();
精彩评论