0

I want to use a logic like this that does not work, why not working

var a = '1==2';
if( a )
{
    alert(1);

} else {
    alert(2);

}

My Code

var arr_logic = {};
arr_logic['rst_content_padding'] = ['rst_general_wrapper', '1==2'];
$.each(arr_logic, function(i, val) {
  if (val[1]) {
    alert(1);
  } else {
    alert(2);
  }
});
Sagar V
  • 12,158
  • 7
  • 41
  • 68

5 Answers5

0

Dont put your boolean in a string :

var a = 1==2;
if( a )
{
    alert(1);

} else {
    alert(2);

}
Zenoo
  • 12,670
  • 4
  • 45
  • 69
  • var arr_logic = {}; arr_logic['rst_content_padding'] = ['rst_general_wrapper', '1==2']; $.each( arr_logic, function( i, val ) { if( val[1] ) { alert(1); } else { alert(2); } }); – Nguyễn Văn Thiên Jun 13 '17 at 10:23
0

just change your code to this :

var a = (1==2);
if( a )
{
    alert(1);
} else {
   alert(2);
}
Emad Dehnavi
  • 3,262
  • 4
  • 19
  • 44
  • var arr_logic = {}; arr_logic['rst_content_padding'] = ['rst_general_wrapper', '1==2']; $.each( arr_logic, function( i, val ) { if( val[1] ) { alert(1); } else { alert(2); } });help me – Nguyễn Văn Thiên Jun 13 '17 at 10:29
0

Non-empty string in JavaScript are truthy, which means their value is true when evaluated in a boolean context (the if statement tries to get a boolean value out of the expression you give to it).

To actually evaluate the expression itself, you must not put it in quotes to create a string, but just leave it without the quotes: 1==2. JavaScript now evaluates this expression to false (because 1 is not equal to 2), and will alert 2:

var a = 1==2;
if (a) {
  alert(1);
} else {
  alert(2);
}

By the way, in most cases, you should use the identity operator to check if two values are equal: 1 === 2 instead of 1 == 2.

PeterMader
  • 6,987
  • 1
  • 21
  • 31
0

Hi you can convert String to executable code in JavaScript by using eval()

var a = '1==2';
if( eval(a) )
{
    alert(1);

} else {
    alert(2);

}
Hardik Leuwa
  • 3,282
  • 3
  • 14
  • 28
0

All you are missing is including a jQuery Library.

Include it from any of the CDN like code.jQuery or googleapis

Try this snippet.

var arr_logic = {};
arr_logic['rst_content_padding'] = ['rst_general_wrapper', 1==2];
$.each(arr_logic, function(i, val) {
  if (val[1]) {
    alert(1);
  } else {
    alert(2);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Sagar V
  • 12,158
  • 7
  • 41
  • 68