Eunice Chia Eunice Chia - 1 year ago 62
Javascript Question

turn string into executable function javascript

var arr = ['abc','xyz'];

$.each(arr, function(i,val){
var val = val; //where I got abc, xyz here
if(some condition){
//run abc function but I don't want to do abc(), possible?


function abc(){}
function xyz(){}

Instead of hardcode my function name like abc(), is there anywhere I can turn string (val) into executable function? by that way I can execute whatever function by just adding values in my array.

Answer Source

Instead of passing in a string, just pass in a reference to the function itself:

var arr = [abc, xyz];

$.each(arr, function(i, fn) {
  if (true) {

function abc() {

function xyz() {
<script src=""></script>