0
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.

Eunice Chia
  • 355
  • 1
  • 11
  • Possible duplicate of [Is there a way to create a function from a string with javascript?](http://stackoverflow.com/questions/7650071/is-there-a-way-to-create-a-function-from-a-string-with-javascript) – alex Jul 22 '16 at 03:15

4 Answers4

0

Assuming your functions are in the global scope, you can access them through window[functionname]():

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

$.each(arr, function(i,val){
  window[val]();
});

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

function xyz(){
  console.log('In xyz()');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79
0

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>
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
0

Both the functions should be a part of a common parent object. So that can be accessed by their property name. Here both are part of the window Object.

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

$.each(arr, function(i, val) {
  if (true) { // some condition.
    window[val]();
  }

});

function abc() {
  console.log('Inside the FN abc');
}

function xyz() {
  console.log('Inside the FN xyz');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Ayan
  • 2,300
  • 1
  • 13
  • 28
0

eval(str) will run code that is in the string str. You really need to trust str and make sure that users can get access to it.

Adrian Brand
  • 20,384
  • 4
  • 39
  • 60