我對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();
我想用這種方法的原因是:
- 易於理解和維護。
- 消除了陣列中潛在的多餘匿名函數分配。
任何給定的功能可以被分配給多個陣列單元,例如:
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的內部知識,我會很高興的建議,如何讓函數調用射擊。
非常感謝所有貢獻見解的人。該代碼在幾分鐘內正確工作,分配如下: myMatrix [5] [4] = do_somemore; ..然後使用myMatrix調用[left] [right](); 前者我已經嘗試過,但後者已經逃脫了我:-) – Thug 2011-04-18 15:48:06
請考慮選擇一個答案或添加更多具體信息,如果沒有答案滿足您的問題。 – 2013-07-10 11:04:24