msanabid
msanabid

Reputation: 197

Passing variable value as condition in if statement

I'm working on script where I wanted to pass value as condition in if statement but it is treating is as string. I am not getting why this value is recognized as string. Do I need to extract the info from the array directly?

//extracting date and preparing condition 
function dateArgument () {
var start = $("#start").val();
var end = $("#end").val();
var y;

if(start && end){
    y = ' && arr[i].created.substring(0,10) >= '+start+' && arr[i].created.substring(0,10) <= '+end;
} else {
    y = '';
}
return y;
};

// Using Condition
function count (arr, nameVar, valueVar){
var x = 0;
// Preparing condition 
var contd = '$.trim(arr[i][nameVar]) == valueVar'+dateArgument();
console.log(contd);
var start = $("#start").val(); 
var end = $("#end").val();

for (i=0; i < arr.length; i++){
    // using prepared condition
             if (contd) {
        x++;
    }
}
return x;
};

// using prepared condition
function mapData (){
  $.ajax({
url:'http://192.168.2.20:8020'+partUrl('province')+partUrl('activity')+partUrl('priority')+partUrl('status'),
type: 'GET',
dataType: 'json',
success: function (data){
    //Using code here
    console.log(count(data,'priority','HighclearLayers();
    createPins(data);
    //summaryValues(data);
    }   
})
};

Upvotes: 0

Views: 4738

Answers (2)

gurvinder372
gurvinder372

Reputation: 68413

I am not getting why this value is recognized as string

It is indeed a String, make it a function to be invoked later

var contd = (i) => $.trim(arr[i][nameVar]) == valueVar && dateArgument(i);

and use it as

 if ( contd(i) )

Also change dateArgument as

function dateArgument () 
{
    var start = $("#start").val();
    var end = $("#end").val();
    var y = () => true;

    if(start && end){
        y = (i) => arr[i].created.substring(0,10) >= start && arr[i].created.substring(0,10) <= end;
    } 
    return y;    
};

Upvotes: 2

Zammy
Zammy

Reputation: 573

It's simple enough. You cannot use a string as a condition. If you really need to, use eval(). But remember, eval is evil!

if (eval(contd)) {
  x++;
}

Better solution: use real conditions instead of string conditions

if(start && end){
    //solve the first part of your condition here
    //this will return a boolean
    y = arr[i].created.substring(0,10) >= start && arr[i].created.substring(0,10) <= end;
} else {
    y = true;
}

//later prepare the condition it like this
//this will also return a boolean
var contd = $.trim(arr[i][nameVar]) == valueVar && dateArgument();

Upvotes: 1

Related Questions