2011-04-18 62 views
2

我對JavaScript很陌生,但這個話題似乎只吸引了很少的論壇關注。給定一些簡單的函數:使用JavaScript從數組中激發命名函數?

function do_something(){...}; 
function do_somemore(){...}; 
function do_something_else(){...}; 

我期待能夠明確地將這些分配給(這裏是2D)數組中的單元格。

myMatrix[5][3] = do_something(); 
myMatrix[5][4] = do_somemore(); 
myMatrix[5][5] = do_something_else(); 

我想用這種方法的原因是:

  1. 易於理解和維護。
  2. 消除了陣列中潛在的多餘匿名函數分配。
  3. 任何給定的功能可以被分配給多個陣列單元,例如:

    myMatrix[2][6] = do_somemore(); 
    myMatrix[5][4] = do_somemore(); 
    myMatrix[6][3] = do_somemore(); 
    

不幸的是,調用諸如以下(基於各種論壇實例中,再加上一點點「吸,看看「)都失敗了。

x = myMatrix[5][4]do_somemore();   -> "missing ; before statement" 
x = (myMatrix[5][4])do_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" 

因爲我沒有JavaScript的內部知識,我會很高興的建議,如何讓函數調用射擊

+0

非常感謝所有貢獻見解的人。該代碼在幾分鐘內正確工作,分配如下: myMatrix [5] [4] = do_somemore; ..然後使用myMatrix調用[left] [right](); 前者我已經嘗試過,但後者已經逃脫了我:-) – Thug 2011-04-18 15:48:06

+0

請考慮選擇一個答案或添加更多具體信息,如果沒有答案滿足您的問題。 – 2013-07-10 11:04:24

回答

2

你應該爲它們分配是這樣的:

myMatrix[5][3] = do_something; 
+1

確實。目前,OP正在調用函數並將返回的值分配給矩陣。 – 2011-04-18 09:14:10

+1

調用這個函數的正確語法是'x = myMatrix [5] [3]();'。另請注意,這些括號稱爲「函數調用操作符」。 – 2011-04-18 09:20:09

0
myMatrix[5][3] = do_something; 

你的方式將其值設置爲函數的結果!

0

我不是你所追求的完全清楚,但:

首先,纔可以賦值給一個數組,該數組必須存在:

var myMatrix = []; 
myMatrix[5] = []; 
myMatrix[5][3] = … // Then you can assign something 

然後,如果要指定功能的返回值

myMatrix[5][3] = do_something(); 

或者,如果你想要分配函數本身

myMatrix[5][3] = do_something; 

...,然後調用它和它的返回值賦給x

var x = myMatrix[5][3](); 

...這是相同的,只是其功能thisvar x = do_something()myMatrix[5]而不是window

0
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]();