Eunice Chia Eunice Chia - 4 months ago 13
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

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) {
    fn();
  }
});

function abc() {
  console.log('abc');
}

function xyz() {
  console.log('xyz');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>