pmirnd pmirnd - 1 year ago 71
Javascript Question

Passing condition to a var in javascript

I don't know how to solve this. I need something like this:

var condition;
if (a==1) //a comes from another part
condition = "arr3[cliente].año == year";
if (a==2)
condition = "arr3[cliente].año == year && arr3[cliente].sic"

//now another if

if (condition){
//rest of code

I need different conditions depending some previous values, the code inside the last if is always the same, so I don't need:

if (arr3[cliente].año == year)
// code
else if (arr3[cliente].año == year && arr3[cliente].sic)
// code

How can I do it?

Answer Source

Just assign the result of the expressions to the variable (currently you are assigning a string). The expression doesn't have to be inside the if statement, the result is what's important:

var condition;
if (a==1)
    condition = arr3[cliente].año == year;
if (a==2)
    condition = arr3[cliente].año == year && arr3[cliente].sic;

// It this point `condition` will either have the value `undefined`, `true` or `false`.    
if (condition) {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download