Slevin
Slevin

Reputation: 4232

How to create dynamic if-conditions

I want to make a dynamic filter method, but don't know how to include conditions dynamically.

Example

var do_test_1 = true,
    do_test_2 = false,
    do_test_3 = true;

Now there are three tests:

if (foo == bar)  // test 1
if (john == doe) // test 2
if (jane == doe) // test 3

Now I want to build a dynamic if clause, based on the do_test vars.

Real use case

I have a list of tasks and want to filter them:

I played around with the filter method, but I only get it working with an OR logic (show tasks that are assigned to me or have a high priority):

var $show = $tasks.filter(function(index, task) {
  var $task = $(task);
  return ((task.data('assigned') && filters['mytasks']) || (task.data('priority') == 3 && filters['priority']))
});

Upvotes: 2

Views: 4841

Answers (1)

Amit Joki
Amit Joki

Reputation: 59292

use eval() function

for(var i=0;i<3;i++){
    var f=i+1;
    eval("if(f==i+1){alert(i);}");   
}

Demo: http://jsfiddle.net/ke42b/2/

This is just a tip on how to create dynamic if conditions. Now you know how to create dynamic if conditions.

Code accordingly to your needs !

Upvotes: 3

Related Questions