Home > Mobile >  Turn array element into a function call
Turn array element into a function call

Time:10-23

This is either a dumb question or one without an answer

I want to call a function by using an element in an array as a way to match the function name

i.e

   var arr = ['one', 'two', 'three'];
   arr[1]();

   function two() { console.log('hello'); }

obviously this doesn't work, and I get "arr[1] is not a function". But is there a trick?

CodePudding user response:

Put the function references into the array - instead of their names as strings.

const arr = [one, two, three];
arr[1]();

function one() {console.log('hello one'); }
function two() {console.log('hello, this is two!'); }
function three() {console.log('hello three'); }

CodePudding user response:

You can use eval() to do it

var arr = ['one', 'two', 'three'];
eval(arr[1] '()');

function two() { console.log('hello'); }

Or using window

var arr = ['one', 'two', 'three'];
window[arr[1]]();

function two() { console.log('hello'); }

CodePudding user response:

You can use a functions Object and declare functions from that. Global functions are always a property of window (the global scope in a browser), so you can refer to them using window[functionName]

const functions = {
  one: _ => console.log(`function one`),
  two: _ => console.log(`function two`),
  three: _ => console.log(`function three`)
};

const [one, two, three] = Object.values(functions);
// call 'one'
one();

// or (not advisable) as global (so: window) properties
const names = [`winOne`, `winTwo`, `winThree`];
const [win1, win2, win3] = names.map(n => window[n]);

// call 'win3'
win3();

function winOne() { console.log(`function winOne`); }
function winTwo() { console.log(`function winTwo`); }
function winThree() { console.log(`function winThree`); }

  • Related