javascript 関数(function)を変数を使って実行する
- 2021.01.14
- javascript

javascriptで、関数(function)を変数を使って実行する方法を記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
作成した関数を変数で実行
以下のように、変数を関数名と実行することはできない
1 2 3 4 5 6 7 |
function hoge() { console.log('hoge'); } // strにhogeを代入 const str = 'hoge'; str(); |
以下のように、windowを利用すれば変数を関数名として利用することができます。
1 2 3 4 5 6 |
function hoge() { console.log('hoge'); } const str = 'hoge'; window[str](); // hoge |
下記でも、可能です。
1 2 3 4 5 6 |
function hoge() { console.log('hoge'); } const str = [hoge]; str[0](); // hoge |
‘use strict’を指定してもエラーにはなりません。
これを利用すれば、以下のように一括で複数の関数を実行することが可能になります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function hoge_1() { console.log('hoge1'); } function hoge_2() { console.log('hoge2'); } for (var i = 1; i < 3; i++) { window['hoge_'+i]() // hoge1 hoge2 } // または下記 const arr = [hoge_1, hoge_2] for (var i = 0; i < 2; i++) { arr[i](); // hoge1 hoge2 } |
アロー関数を使用
アロー関数の場合は、windowを使用するとエラーになりますが、
1 2 3 4 5 6 7 8 9 10 |
const hoge_1 = () => { console.log('hoge1'); } const hoge_2 = () => { console.log('hoge2'); } for (var i = 1; i < 3; i++) { window['hoge_'+i]() // Uncaught TypeError: window[("hoge_" + i)] is not a function } |

配列を使用すれば、エラーにはなりません。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const hoge_1 = () => { console.log('hoge1'); } const hoge_2 = () => { console.log('hoge2'); } const arr = [hoge_1, hoge_2] for (var i = 0; i < 2; i++) { arr[i](); // hoge1 hoge2 } |
-
前の記事
python ファイルを削除する 2021.01.14
-
次の記事
CentOs7 Rubyをインストールする手順 2021.01.14
コメントを書く